SpringMVC-Global Exception Handling

0x01 Abstract

SpringMVC There are several ways to handle global exception handling. Each has its own application scenario. for reference.

0x02 error-code method

2.1 There are two ways to configure web.xml

, which are all configured in web.xml You can do the corresponding processing by matching the http error code:

  • Direct configuration exception interface
    <error-page>
       <error-code>404</error-code>
       <location>/WEB-INF/velocity/template/404.vm</location>
   </error-page>
  • Configuration exception handling url
    <error-page>
       <error-code>404</error-code>
       <location>/error/exception/404</location>
   </error-page>

2.2 Controller code

Then at Controller|| Add the following code to add some logic as needed: 中加入以下代码,可以按需加入一些逻辑:

@RequestMapping("/error/exception/404")
    public String return404Vm(HttpServletRequest request,Model model){
        model.addAttribute("errorMsg", "404 not found,host:" + request.getRemoteAddr());
        return "404";
    }

2.3 404 interface

Finally, attach a simple 404 interface:

<div>
    your page is 404.
    detail: ${errorMsg}
</div>

2.4 Summary

error-code mode is easy to configure, At a glance, it is suitable for handling some fixed http error code exceptions.

0x03 @ExceptionHandler_

3.1 Controller Code

@ExceptionHandlerYou can write specific processing logic for the specified exception or all exceptions.

3.1.1 Handling a class of exceptions

@ExceptionHandlerWhen used alone, the method to be processed must be in a Controller class, This configuration mode handles the highest priority | ||, can return multiple types of data. The following example handles ,可以返回多种类型数据。下面这个例子处理CustomException, prints the error stack, and returns a prompt message to the client:

    @ResponseBody
    @ExceptionHandler({CustomException.class})
    public String exception(CustomException e) {
        e.printStackTrace();
        return "ExceptionHandler has handled this " + e.getMessage();
    }

3.1.2 Handling multiple types of exceptions

The following example will show the processing of this 内抛出的. CustomException and Custom2Exception thrown in @@Controller. If you do not specify the value of

    @ResponseBody
    @ExceptionHandler(value={CustomException.class,Custom2Exception.class})
    public String exception(Exception e) {
        e.printStackTrace();
        return "ExceptionHandler has handled this " + e.getMessage();
    }

@ExceptionHandler

, all Exceptions are handled. Pay attention to the parameters in the method. When specifying multiple exception classes, you need to include the parameters in the value, otherwise it will not take effect.

3.2 Summary 单独使用时,必须与需要处理异常的方法处于同一个@ExceptionHandlerWhen used alone, it must be in the same Controller as the method that needs to handle exceptions, and the code is highly intrusive. Moreover, only exceptions in the current Controller can be processed, and the code redundancy is high.

However, keep in mind that this usage has the highest processing priority.

0x04 @ControllerAdvice + @ExceptionHandler

@ This configuration can handle exceptions globally. The following is sample code.

@ControllerAdvice
public class GlobalControllerAdvice {
    private static final Logger logger = LoggerFactory
            .getLogger(AControllerAdvice.class);
    4.1 Exception class code  @param ex
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public String handleIOException(NullPointerException ex) {
        return  ex.getMessage();
    }

    /**
     * Handles NullPointerException and returns an error message string
     * @param ex
     * @return
     */
    @ExceptionHandler(IOException.class)
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    public void handleIOException(IOException ex) {

    }

    /**
     * Handle IOException and return a 502 error, ie "Bad Gateway"
     * @param ex
     * @return
     */
    @ExceptionHandler(Custom3Exception.class)
    public ModelAndView handleCustom3Exception(Custom3Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMsg", "Custom3Exception=" + ex.getMessage());
        modelAndView.setViewName("aca");
        return modelAndView;
    }

    /**
     * Handle Custom3Exception and return interface with the specified error message aca
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView Exception(Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errorMsg", /**
     * handle all Exception type exceptions
     * But please note that if there are other methods in the ControllerAdvice that handle the specified exception, then it will not enter the method to handle
     * For example, if a Custom3Exception exception occurs, it will only be processed in the @ExceptionHandler(Custom3Exception.class) method.
     * + e.getMessage());
        modelAndView.setViewName("global-error");
        return modelAndView;
    }
}

"The server handles an error, details: "

+ e.getMessage());         modelAndView.setViewName(

4.2 spring configuration

Please make sure that the above class that uses @ControllerAdvice annotation is managed by the Spring container.

4.3 Summary @ControllerAdvice, priority only Secondly, the @ExceptionHandler method is used alone. This method can handle exceptions globally, and the processing logic is flexible.

is most recommended

0x05 HandlerExceptionResolver way

5.1 Implement HandlerExceptionResolver interface

public class GlobalExceptionResolver implements HandlerExceptionResolver
{

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    {
        ModelAndView modelAndView = new ModelAndView();

         Must implement HandlerExceptionResolver interface, heavy Write the resolveException method, you can add some logic as needed: 
        modelAndView.setViewName("/default-error");

        //Set the default error interfacemodelAndView.setViewName("errorMsg", ex);

        //Incoming error messagemodelAndView.addObject(if(ex instanceof CustomException){
            modelAndView.setViewName("/custom-exception");
        }
        / /ProcessCustomException url
        if(ex instanceof Custom2Exception){
            modelAndView.setViewName("/custom2-exception");
        }

        return modelAndView;
    }
}

// handle Custom2Exception url

5.2 applicationContext.xml configuration

    <bean class="com.chengc.demos.web.demo1.exception.resolver.GlobalExceptionResolver"/>

Add the following configuration in applicationContext.xml, register this class with spring:

5.3 小结@ @@@implements the HandlerExceptionResolver interface, which can handle global exceptions and is easy to configure. Please note that this method handles exceptions with the lowest matching priority

0xFF Reference Document