Spring Boot 2.X (XI): Global Exception Handling (reprint)

Foreword

In the Java Web system development, regardless of the Controller layer, Service layer or layers Dao, it is likely to throw an exception. If coupled with a variety of try catch exception handling code in each process, that makes the code is very complicated. In Spring MVC, we can put all kinds of exception handling decoupled from the individual approach, unified processes and maintains exception information.

Exception trap handling in Spring MVC in a global solutions are usually two ways:

1. @ControllerAdvice + @ExceptionHandler annotations for exception handling global Controller layer.

2. The method of implementing the resolveException org.springframework.webb.servlet.HandlerExceptionResolver interface.

Use @ControllerAdvice + @ExceptionHandler comment

1. Define a unified exception handling class

@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
        log.error("ExceptionHandler ===>" + e.getMessage());
        e.printStackTrace();
        // 这里可根据不同异常引起的类做不同处理方式
        String exceptionName = ClassUtils.getShortName(e.getClass());
        log.error("ExceptionHandler ===>" + exceptionName);
        ModelAndView mav = new ModelAndView();
        mav.addObject("stackTrace", e.getStackTrace());
        mav.addObject("errorMessage", e.getMessage());
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("forward:/error/500");
        return mav;
    }
}

Wherein the @ExceptionHandler (value = Exception.class) capture abnormal value can be customized, as follows:

Types of description
NullPointerException When an application tries to access an empty object, Thrown
SQLException Provide information about database anomalies access error or other error messages
IndexOutOfBoundsException Throws index indicating a sort (e.g. sorted array, a string, or a vector) is out of range
NumberFormatException When the application tries to convert a string into a numeric type, but that the string can not be converted into the appropriate format, the exception thrown
FileNotFoundException When you try to open the file specified pathname failed Thrown
IOException When some kind of I / O exception This exception is thrown. Such failed or interrupted I / O operation abnormality generated generic class
ClassCastException When trying to cast an object is not an instance of a subclass Thrown
ArrayStoreException Trying to store the wrong type to throw an exception when an object array
IllegalArgumentException Thrown to indicate that passed an illegal or incorrect parameter to the method
ArithmeticException When the exceptional arithmetic condition occurs, Thrown. For example, an integer "divide by zero" throws an instance of this class
NegativeArraySizeException If the application tries to create an array with negative size, Thrown
NoSuchMethodException When a particular method can not be found, Thrown
SecurityException By the security manager throws an exception, indicate a security violation
UnsupportedOperationException When the requested operation is not supported, the exception thrown
RuntimeException Those abnormal super class may be thrown during the normal operation of the Java Virtual Machine

When capturing the exception type of response, it will enter the defaultErrorHandler () method of logic: the abnormality information into the Model, to jump / error / 500 requests URL.

2. anomalies show

View Controller Configuration

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 视图控制器配置
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {   
        registry.addViewController("/").setViewName("/index");//设置默认跳转视图为 /index
        registry.addViewController("/error/500").setViewName("/error/500");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
        
    }
    
}

View Template

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Exception</h1>
<h3 th:text="${url}"></h3>
<h3 th:text="${errorMessage}"></h3>
<p  th:each="line : ${stackTrace}" th:text="${line}">  </p>
</body>
</html>

3. Test Exception class

@Controller
public class TestController {

    @GetMapping("/index")
    public String hello() {
        int x = 1 / 0;
        return "hello";
    }
}

4. Run the test

Browser to access: http: //127.0.0.1: 8080 / index
www.wityx.com

@ControllerAdvice can also bind @ModelAttribute, used with @ InitBinder annotation to achieve binding global data and global data pre-processing and other functions.

Achieve HandlerExceptionResolver Interface

1. Define a unified exception handling class

@Component
public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {

    private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        Exception e = new Exception();
        //处理 UndeclaredThrowableException
        if (ex instanceof UndeclaredThrowableException) {
            e = (Exception) ((UndeclaredThrowableException) ex).getUndeclaredThrowable();
        } else {
            e = ex;
        }
        e.printStackTrace();
        //这里可以根据不同异常引起的类做不同处理方式
        String exceptionName = ClassUtils.getShortName(e.getClass());
        if(exceptionName.equals("ArrayIndexOutOfBoundsException")) {
            log.error("GlobalHandlerExceptionResolver resolveException ===>" + exceptionName);
            ModelAndView mav = new ModelAndView();
            mav.addObject("stackTrace", e.getStackTrace());
            mav.addObject("exceptionName", exceptionName);
            mav.addObject("errorMessage", e.getMessage());
            mav.addObject("url", request.getRequestURL());
            mav.setViewName("forward:/error/500");
            return mav;
        }
        return null;
    }

}

When an exception occurs UndeclaredThrowableException usually recall a scene or scenes using JDK dynamic proxies in the RPC interface. If you do not pre-conversion processing, testing caught exception was UndeclaredThrowableException, rather than a true exception object.

2. The above exception information to show

3. Test Exception class

@Controller
public class TestController {

    @GetMapping("/test")
    public String test() {
        String[] ss = new String[] { "1", "2" };
        System.out.print(ss[2]);
        return "hello";
    }

}

4. Test Run

Before the test the first @ControllerAdvice comment.
Browser to access: http: //127.0.0.1: 8080 / test
www.wityx.com

Sample Code

github

Cloud code

Non-specific instructions, article belongs Asagiri Qing Han all, please indicate the source.

Original title: Spring Boot 2.X (XI): Global Exception Handling

Original Address: https://www.zwqh.top/article/info/20

Guess you like

Origin www.cnblogs.com/xyy2019/p/11743734.html