Chapter 4 of SpringBoot: Handling global exceptions

 

We talked about handling global exceptions in spring MVC. Of course, spring boot also has global exception handling.

I Custom processing common 404 and 505 pages.

For example, if we enter a path that does not exist in the program, we will jump to the interface that cannot be found in 404.

Input: http://localhost:8080/j/show1

In fact, springboot also comes with custom processing 404 HTML and 500 HTML exception.

Just put error. In the resources/templates directory HTML, you can customize the page and jump,

However, the premise is that the rendering template in the previous chapter needs to be enabled, or the thymeleaf template.

 

If you want to accurately locate 404 For the status code of HTML or 505html, you need to create an error file package under resources/templates and put it into 404 HTML and 500 html

 

II Override custom exception handling: BasicErrorController

We can inherit the BasicErrorController class and override the method. To customize the 404 pages you need

ErrorPageController.java :

There are five attributes in errorMap:

Timestamp: timestamp

Status: status 404

Error: error not found

Message: no message

Path: path error

package com.SpringBoot.demo.error;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;

public class ErrorPageController extends BasicErrorController {

	public ErrorPageController(ErrorAttributes errorAttributes, ErrorProperties errorProperties,
			List<ErrorViewResolver> errorViewResolvers) {
		super(errorAttributes, errorProperties, errorViewResolvers);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
		// TODO Auto-generated method stub
		Map<String, Object> errorMap = super.getErrorAttributes(request, includeStackTrace);
		errorMap.remove("message");
		errorMap.remove("path");
		return errorMap;
	}
	
	

}

After rewriting, we need to configure it to replace the global exception handling function in spring.

ErrorConfiguration.java:

package com.springboot.demo.SpringBootDemoProject.error;

import java.util.List;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ErrorConfiguration {

	@Bean
	public ErrorPageController basicErrorController(ErrorAttributes errorAttributes, 
			ServerProperties serverProperties, 
			ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
		return new ErrorPageController(errorAttributes, serverProperties.getError(), 
				errorViewResolversProvider.getIfAvailable());
	}
}
 

 

III Exception handling often used in spring MVC: @ ControllerAdvice + @ExceptionHandler

For example, you want to handle null pointers, missing classes and other exceptions:

MyExceptionHandler.java: use annotation to configure NullPointerException exception

package com.SpringBoot.demo.error;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class MyExceptionHandler {
	@ExceptionHandler
	public ModelAndView exp(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		
		if(ex instanceof NullPointerException) {
			modelAndView.setViewName("error/error_null");
		}else {
			modelAndView.setViewName("error/error_other");
		}
		
		return modelAndView;
	}

}

Jump page:

error_null.jsp:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>error_null title here</title>
</head>
<body>
<h1>error_null . NullPointerException</h1>

</body>
</html>

error_other.jsp:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>error_null . NullPointerException</h1>
</body>
</html>

 

Null pointer exception test control layer:

package com.SpringBoot.demo.error;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("e")
public class ErrorTestController {
	@RequestMapping("show")
	public String show(ModelMap model) {
		
		 String str = null;
		 str.charAt(0);
		 
		//String[] str = {"22", "33"}; String ss = str[2];
		
		return "thymeleaf";
	}
}

Test results:

In conclusion, only one file is needed to capture and intercept all NullPointerException exceptions of the whole project and jump to the exception page defined by yourself

 

Of course, the @ ControllerAdvice + @ExceptionHandler method can also jump to the page separately:

@ExceptionHandler(NullPointerException.class) can specify exceptions, and other exceptions will jump to unspecified exceptions

package com.SpringBoot.demo.error;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class MyExceptionHandler {
	/*@ExceptionHandler
	public ModelAndView exp(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		
		if(ex instanceof NullPointerException) {
			modelAndView.setViewName("error/error_null");
		}else {
			modelAndView.setViewName("error/error_other");
		}
		
		return modelAndView;
	}*/
	
	@ExceptionHandler(NullPointerException.class)
	public ModelAndView exp(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		modelAndView.setViewName("error/error_null");	
		return modelAndView;
	}
	
	@ExceptionHandler
	public ModelAndView exp1(Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		modelAndView.setViewName("error/error_other");	
		return modelAndView;
	}
}

 

IV SimpleMappingExceptionResolver global exception handling

MySimpleMappingExceptionResolver.java :

This class is also a Configuration class, which needs to be configured into the spring container using @ Configuration. The class used is SimpleMappingExceptionResolver

Properties: configuration file, which is used to save exception information and exception interface

package com.SpringBoot.demo.error;

import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

@Configuration
public class MySimpleMappingExceptionResolver {
	
	@Bean
	public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
		SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
		Properties properties = new Properties();
		properties.put("java.lang.NullPointerException", "error/error_null");
		simpleMappingExceptionResolver.setDefaultErrorView("error/error_other");
		simpleMappingExceptionResolver.setExceptionMappings(properties);
		return simpleMappingExceptionResolver;
	}
}

 

We still pass:

ErrorTestController.java for testing

package com.SpringBoot.demo.error;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("e")
public class ErrorTestController {
	@RequestMapping("show")
	public String show(ModelMap model) {
		
		 String str = null;
		 str.charAt(0);
		 
		//String[] str = {"22", "33"}; String ss = str[2];
		
		return "thymeleaf";
	}
}

Other configuration files need to be shielded during the test. The test successfully jumped to nullpointerException

 

V Implement handler exception resolver processor in mvc

Override the resolveException method by implementing the HandlerExceptionResolver interface

package com.SpringBoot.demo.error;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Configuration
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		// TODO Auto-generated method stub
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("errorInfo", ex.getMessage());
		
		if(ex instanceof NullPointerException) {
			modelAndView.setViewName("error/error_null");
		}else {
			modelAndView.setViewName("error/error_other");
		}
		return modelAndView;
	}

}

The effect is the same

 

Keywords: Java Spring Spring Boot servlet

Added by Loki_d20 on Fri, 11 Feb 2022 12:58:23 +0200