Spring MVC exception handling

Keywords: Java Spring Spring MVC mvc

Spring MVC has three ways to handle exceptions:

  1. Use the simple exception handler SimpleMappingExceptionResolver provided by Spring MVC.
  2. Implement the exception handling interface HandlerExceptionResolver of Spring and customize your own exception handler.
  3. Use the @ ExceptionHandler annotation to implement exception handling

1. @ExceptionHandler 

  Local exception handling can only handle exceptions in the specified Controller.

Example 1: the following is implemented using the @ ExceptionHandler annotation. Define a testExceptionHandle method that may have exceptions during processing.

The exception is: ArithmeticException

@ExceptionHandler({ ArithmeticException.class })
public String testArithmeticException(Exception e) {
    System.out.println("Print error message ===> ArithmeticException:" + e);
    // Jump to the specified page
    return "error";

  Note: this annotation is not added to the method that generates the exception, but to the method that handles the exception.

When this error occurs, it will jump to the error.jsp page

And output the error message System.out.println("print error message = = = > arithmeticexception:" + e) on the console;

@The method priority problem defined by the ExceptionHandler annotation: for example, a NullPointerException occurs, but the declared exceptions include RuntimeException and Exception. At this time, the @ ExceptionHandler annotation method with the shallowest inheritance depth will be found according to the recent inheritance relationship of the Exception, that is, the method marked with RuntimeException.

It is marked as an exception handling method by @ ExceptionHandler. No other formal parameters can be set in the method. However, you can use ModelAndView to pass data to the front desk.

Using local exception handling, you can only handle exceptions in a Controller. If you need to handle all exceptions uniformly, you can use the following two methods.

2. HandlerExceptionResolver

Spring MVC passed   HandlerExceptionResolver handler exceptions, including processor exceptions, data binding exceptions, and exceptions that occur during controller execution. HandlerExceptionResolver has only one interface method

Spring MVC passed   HandlerExceptionResolver handler exceptions, including processor exceptions, data binding exceptions, and exceptions that occur during controller execution. HandlerExceptionResolver has only one interface method

Create an implementation class MyExceptionHandler of the HandlerExceptionResolver interface in the net.biancheng.exception package. The code is as follows.

package net.biancheng.exception;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
public class MyExceptionHandler implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            Exception arg3) {
        Map<String, Object> model = new HashMap<String, Object>();
        // Turn to different pages according to different errors (unified processing), that is, the corresponding relationship between exceptions and views
        if (arg3 instanceof ArithmeticException) {
            return new ModelAndView("error", model);
        return new ModelAndView("error-2", model);

  Add the following code to the springmvc-servlet.xml file.

<!--trusteeship MyExceptionHandler-->
<bean class="net.biancheng.exception.MyExceptionHandler"/>

3. SimpleMappingExceptionResolver

Global exception handling can be used   SimpleMappingExceptionResolver. It maps the exception class name to the view name, that is, when an exception occurs, the corresponding view is used to report the exception.
Configure the global exception in springmvc-servlet.xml. The code is as follows.

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <!-- Define the default exception handling page, which is used when the exception type is registered -->
    <property name="defaultErrorView" value="error"></property>
    <!-- Define the variable name used by the exception handling page to obtain exception information. The default name is exception -->
    <property name="exceptionAttribute" value="ex"></property>
    <!-- Define exceptions that need special handling, using class name or full pathname as key,Exception page name as value -->
    <property name="exceptionMappings">
            <prop key="ArithmeticException">error</prop>
            <!-- Here you can also continue to extend the handling of different exception types -->

In general, we configure some specific exceptions through

  1. <props>
  2. <prop key="ArithmeticException">error</prop>
  3. <!-- Here, you can also continue to expand the processing of different exception types -- >
  4. </props>

Through this configuration, in the prop, the key is configured as the corresponding exception, and the subsequent error is the jump interface of the corresponding jsp, which is similar to the previous requrstMapping; Is if the code throws   When ArithmeticException is an exception, the system will automatically jump to the error interface


Posted by rigi2 on Tue, 26 Oct 2021 19:20:24 -0700