Summary of Java knowledge points: If you want to see it, you can enter it from here
Table of contents
2.14. Exception handling
2.14.1, define the error page
SpringBoot's default exception handling mechanism: Once an exception occurs in the program, SpringBoot will request the url of /error. In SpringBoot, a BasicExceptionController is provided to handle the /error request, and it will jump to the page that displays the exception by default to display the exception information.
![image-20220925134115681](https://yudejava.oss-cn-hangzhou.aliyuncs.com/typora/202303101428729.png)
However, we can add an error page in resources/templates/ to customize the exception page. The name and path cannot be changed, because BasicExceptionController jumps to this path by default.
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>恭喜你啊,你进入了异常页面</h1>
</body>
</html>
![image-20220925134544868](https://yudejava.oss-cn-hangzhou.aliyuncs.com/typora/202303101428601.png)
2.14.2. Local abnormalities
In SpringBoot, you can use @ExceptionHandler
annotations to handle local exceptions. It defines a method in the Controller, internally writes the processing logic after the exception occurs, and then adds the @ExceptionHandler(value={}) annotation to the method to indicate the exception to be caught, and then This method is used when an exception occurs in this Controller.
-
define an error page
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>恭喜你啊,你进入了异常页面</h1> <p th:text="${msg}"></p> </body> </html>
-
Controller: do not write
@ExceptionHandler
@Controller @RequestMapping("/test") public class HelloController { @GetMapping("/hello") public String hello(String name){ int i = 9/0; return "login"; } }
-
At this time, add annotations in the Controller
@ExceptionHandler
, and complete the relevant methods, and handle them when an exception occurs@Controller @RequestMapping("/test") @Slf4j public class HelloController { @GetMapping("/hello") public String hello(String name){ int i = 9/0; return "login"; } @ExceptionHandler(value = { Exception.class}) public String exceptionHandling(Model model,Exception e){ model.addAttribute("msg","发生了异常:"+e.getMessage()); log.info(e.getMessage()); return "error"; } }
2.14.3. Global exceptions
Annotations are used to @ExceptionHandler
handle local exceptions, which are only valid in one Controller. Generally, we require global exception handling, which is valid for all Controllers.
Create a class that specifically handles exceptions, then use annotations on the class @ControllerAdvice
, and then create exception handling methods internally, and @ExceptionHandler
after adding annotations to the methods, this class can handle global exceptions.
-
Define a global exception handling class
@ControllerAdvice @Slf4j public class HandleException { @ExceptionHandler public String exceptionHandling(Model model, Exception e){ model.addAttribute("msg","全局异常处理:"+e.getMessage()); log.info(e.getMessage()); return "error"; } }
-
Remove the original local exception method in Controller
@Controller @RequestMapping("/test") public class HelloController { @GetMapping("/hello") public String hello(String name){ int i = 9/0; return "login"; } }
When using global exception handling, you can also use local exception handling, which has a higher priority than global exception handling. That is to say, after a Controller defines a local exception handling method, it will no longer execute global exception handling.
The above example adds a local exception handling method to the Controller
@Controller
@RequestMapping("/test")
public class HelloController {
@GetMapping("/hello")
public String hello(String name){
int i = 9/0;
return "login";
}
@ExceptionHandler(value = {
Exception.class})
public String exceptionHandling(Model model,Exception e){
model.addAttribute("msg","局部异常处理:"+e.getMessage());
return "error";
}
}
![image-20220925171857441](https://yudejava.oss-cn-hangzhou.aliyuncs.com/typora/202303101428376.png)
2.14.4, abnormal configuration class
In addition to @ControllerAdvice
+ @ExceptionHandler
annotations for global exception handling, you can also create a SimpleMappingExceptionResolver object through the configuration class to handle exceptions, which is also global.
But using SimpleMappingExceptionResolver can't get the exception object, can't get the exception message, but it can judge multiple exception types in one method, and jump to different pages according to different exceptions.
@Configuration
public class MyExceptionConfig {
@Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){
System.out.println("处理异常");
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
//参数:异常类型全限定名,异常的视图名称
properties.put("java.lang.Exception","error2");
// properties.put()可以写多个,使不同的异常类型跳转到不同的异常页面
resolver.setExceptionMappings(properties);
return resolver;
}
}
Still use the above Controller, but note that both global and local exceptions need to be deleted, and SimpleMappingExceptionResolver has the lowest priority among the three.
2.14.5. Exception handling interface
By implementing HandlerExceptionResolver
the interface, exceptions can also be handled. This processing method can not only obtain the exception object, but also jump to different pages according to different exceptions.
@Configuration
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", "HandlerExceptionResolver 接口处理异常:"+ex.getMessage());
//可以根据不同的异常类型进行跳转
if(ex instanceof ArithmeticException){
modelAndView.setViewName("error");
}else if(ex instanceof NumberFormatException){
modelAndView.setViewName("error2");
}
return modelAndView;
}
}
2.14.6, priority and distinction
The priorities of the four kinds of exception handling are: local exception handling of @ExceptionHandler > global exception handling of @ControllerAdvice
+ @ExceptionHandler
> global exception handling of HandlerExceptionResolver interface > global exception handling of SimpleMappingExceptionResolver
@ExceptionHandler is local exception handling, which can only handle the exception of a single Controller, and the other three can handle global exceptions
HandlerExceptionResolver
, SimpleMappingExceptionResolver
Different jumps can be made for different types of exceptions in one method, and the global exception handling and local exception handling of @ControllerAdvice
+ need multiple methods to realize different exception types and jump to different pages.@ExceptionHandler
@ExceptionHandler
SimpleMappingExceptionResolver cannot obtain exception objects, and the other three types can obtain exception objects