SpringBoot There are five ways to handle exceptions:
A custom error page
SpringBoot default exception handling mechanism: SpringBoot default has provided a mechanism for handling exceptions. Once the program emerged url abnormal SpringBoot send a request like / error of. To provide a process called BasicExceptionController in springboot in / error requests, and then jump to the default display page to show abnormal abnormal information.
If we need to unify all of the abnormal jump to a custom error page, you need to create error.html page in src / main / resources / templates directory. And add the tag.
<span th:text="${exception}"></span>
Two, @ ExceptionHandle annotations for exception handling
Just add this method in the controller:
1 @ExceptionHandler(value={java.lang.ArithmeticException.class})
2 public ModelAndView arithmeticExceptionHandler(Exception e) {
3 ModelAndView mv = new ModelAndView();
4 mv.addObject("error", e.toString());
5 mv.setViewName("error");
6 return mv;
7 }
Three, @ ControllerAdvice + @ ExceptionHandler annotations for exception handling
Be able to handle exceptions need to create a global exception classes. On the class need to add @ControllerAdvice comment.
1 @ControllerAdvice
2 public class GlobalException {
3 @ExceptionHandler(value={java.lang.ArithmeticException.class})
4 public ModelAndView arithmeticExceptionHandler(Exception e) {
5 ModelAndView mv = new ModelAndView();
6 mv.addObject("error", e.toString());
7 mv.setViewName("error");
8 return mv;
9 }
10 }
Fourth, configure SimpleMappingExceptionResolver handle exceptions
In the global exception class to add a method to complete the process unity exception class
1 @Configuration
2 public class GlobalException {
3 public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
4 SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
5 Properties properties = new Properties();
6 properties.put("java.lang.ArithmeticException", "error");
7 resolver.setExceptionMappings(properties);
8 return resolver;
9 }
10 }
V. custom exception handling HandlerExceptionResolver
HandlerExceptionResolver interface need to achieve global exception class
1 @Configuration
2 public class GlobalException implements HandlerExceptionResolver {
3 @Override
4 public ModelAndView resolverException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
5 ModelAndView mv = new ModelAndView();
6 if(exception instanceof ArithmeticException) {
7 mv.setViewName("error");
8 }
9 mv.addObject("error", exception.toString());
10 return mv;
11 }
12 }