Spring MVC provides us with a unified exception handling mechanism in the following four ways. It's important to note that if we want to use a unified exception handling mechanism, then we don't have to try the exception that needs unified processing. catch... Instead, it is handled uniformly by exception handlers.
First, using Spring MVC to provide us with exception handlers
_In Spring MVC, a Handler Exception Resolver interface is defined to handle exceptions uniformly.
public interface HandlerExceptionResolver { ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex); }
Spring MVC provides us with several implementation classes of Handler Exception Resolver interface, which can be used directly to unify exception handling.
Let's take SimpleMapping Exception Resolver as an example to illustrate the unified handling of exceptions in this way.
_1 Custom exception:
public class MyException extends RuntimeException { private static final long serialVersionUID = 1L; public MyException(String message) { super(message); } }
Configure exception handlers in Spring MVC container configuration file:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <! - Defau lt exception display page: Return to the page when the exception thrown is not the exception type specifically specified in the exception Mappings - > <property name="defaultErrorView" value="error"></property> <! -- Defines the variable name used by the exception handling page to obtain exception information, and the defau lt name is exception - >. <property name="exceptionAttribute" value="ex"></property> <! -- List of exceptions that require special handling: key is the class name or full path name of the exception, and the value is the display page when the exception is thrown - > The key is the class name or full path name of the exception. <property name="exceptionMappings"> <props> <! - Here you configure custom exceptions - >. <prop key="com.bdm.exceptions.MyException">error1</prop> <prop key="com.bdm.exceptions.MyException1">error2</prop> </props> </property> </bean>
Tip:
The location of the ________ exception handling page must be in the prefix directory of the configured view parser
_2_The variables used to get abnormal information on the page should have the same value as the exceptionAttribute attribute, such as getting abnormal information in error1.jsp.
<span style="color: red">${ex.message}</span>
2. Implementation of custom Handler Exception Resolver interface
In addition to using Spring MVC exception handlers directly, we can also customize exception handlers. The way to customize exception handlers is to set up and get richer exception information. The steps are as follows:
_(1) Custom exception handler class: Implementing Handler Exception Resolver interface
public class MyExceptionHandler implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Map<String, Object> model = new HashMap<String, Object>(); // Define variables for page to get exception information model.put("ex", ex); // Here we can put more exception information. // Turn to different pages based on different exceptions if (ex instanceof MyException) { return new ModelAndView("error1", model); } else if (ex instanceof MyException1) { return new ModelAndView("error2", model); } else { return new ModelAndView("error", model); } } }
Configuration of custom exception handlers in Spring MVC containers
<bean class="com.bdm.handlers.MyExceptionHandler" />
_(3) As long as the corresponding exception is thrown in Controller, it will be handled in accordance with the corresponding exception handling method.
3. Use @ExceptionHandler in Controller
_We can add one or more methods annotated with @ExceptionHandler to each Controller class, and of course we can extract a common parent class and define the method in the parent class:
@RestController public class TestController { @RequestMapping("/testException/{id}") public String testException(@PathVariable Integer id) { if (id == 1) throw new MyException(">>>>exception"); return "success"; } @ExceptionHandler public String exp(HttpServletRequest request, Exception ex) { request.setAttribute("ex", ex); request.setAttribute("msg", "yichang"); // Turn to different pages based on different errors if (ex instanceof MyException) { return "error1"; } else if (ex instanceof MyException1) { return "error2"; } else { return "error"; } } }
Tip:
1@ExceptionHandler annotations have a higher priority than custom Handler ExceptionResolver annotations, and exceptions in this Controller will no longer be intercepted by subclasses of Handler ExceptionResolver if handled in the @ExceptionHandler annotation method.
The return value of the method annotated by 2@ExceptionHandler is related to the definition of this class. For example, if @RestController is marked on this class, the return value of the method will be the object itself rather than the address of the page.
The limitation of exception handling in this way is that it can only handle exceptions thrown in the Controller, but not globally. Of course, it can also extract a common parent class to define the method of @ExceptionHandler annotation.
4_In @ExceptionHandler, you can specify exceptions to be handled
@ExceptionHandler(RuntimeException.class) public String exp(HttpServletRequest request, Exception ex) { request.setAttribute("ex", ex); request.setAttribute("msg", "yichang"); // Turn to different pages based on different errors if (ex instanceof MyException) { return "error1"; } else if (ex instanceof MyException1) { return "error2"; } else { return "error"; } }
4. Use @Controller Advice
The @ExceptionHandler approach described above can only handle exceptions thrown in the current Controller. Spring MVC also provides us with @Controller Advice to monitor exceptions thrown in Controller under a specified package. The steps are as follows:
____Definition of Relevant Aspects: Packages for Designating the Role of Aspects
@ControllerAdvice(basePackages = "com.bdm.controllers") public class MyControllerAdvice { @ExceptionHandler(MyException.class) public ModelAndView myExceptionHandler(MyException ex) { ex.printStackTrace(); Map<String, Object> map = new HashMap<>(); map.put("ex", ex); return new ModelAndView("error1", map); } }
_2. Register the section class in the Spring MVC container
<bean class="com.bdm.handlers.MyControllerAdvice" />
(3) Throwing the corresponding exception in Controller: it will be intercepted and handled by the tangent method
@RestController public class TestController { @RequestMapping("/testException/{id}") public String testException(@PathVariable Integer id) { if (id == 1) throw new MyException(">>>>exception"); return "success"; } }
Tip:
1@Controller Advice section class has lower priority than Handler Exception Resolver implementation class.
2@Controller Advice annotation method is not only for exception handling, it can actually monitor all methods in all Controller, specific reference. Spring MVC @Controller Advice