SpringBoot entry series (11) Implementation of unified exception handling SpringBoot entry series (4) Integrated template engine Thymeleaf

The previous section describes how Spring Boot integrates scheduled tasks and how Spring Boot creates asynchronous tasks and scheduled tasks. Unclear friends can take a look at the previous article: " Spring Boot Getting Started Series "

Next, we mainly explain how to use unified exception handling in Spring Boot applications.

 

Why unified exception handling

The development form of the project is the separation of the front end and the back end, which is developed in the form of Restful interface. The exception handling and page business data are returned in json form. However, if exceptions such as database exceptions, Shiro exceptions, Redis exceptions, etc. occur in the background, the front end usually displays a very ugly error page, which is very unfriendly to users, so we need to deal with various system exceptions in a unified way And then return the result we want.

 

 

How to achieve

There are two main methods for Spring Boot to implement unified exception handling:

The first one: use @ControllerAdvice and @ExceptionHandler annotations

The second: use the ErrorController class to achieve.

The way to use ErrorController is relatively simple, so I won't introduce it here. Today I will mainly talk about how to implement unified exception handling using @ControllerAdvice and @ExceptionHandler annotations.

1. Unified Exception Handling

package com.weiz.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.weiz.utils.JSONResult;

@ControllerAdvice
public class GlobalExceptionHandler  {

    public static final String ERROR_VIEW = "error";


    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest reqest, 
            HttpServletResponse response, Exception e) throws Exception {
        
        e.printStackTrace ();
        // Whether ajax request 
        if (isAjax (reqest)) {
             return JSONResult.errorException (e.getMessage ());
        } else {
            ModelAndView mav = new ModelAndView ();
            mav.addObject("exception", e);
            mav.addObject("url", reqest.getRequestURL());
            mav.setViewName(ERROR_VIEW);
            return mav;
        }
    }
    
    public static boolean isAjax(HttpServletRequest httpRequest){
        return  (httpRequest.getHeader("X-Requested-With") != null  
                    && "XMLHttpRequest"
                        .equals( httpRequest.getHeader("X-Requested-With")) );
    }
}

Description:

  1. Annotation @ControllerAdvice indicates that this is a controller enhancement class. When an exception occurs in the controller, it will be intercepted by this interceptor.

  2. The annotation @ExceptionHandler defines the intercepted exception class, which can obtain the thrown exception information. Here you can define multiple interception methods to intercept different exception classes, and you can get the information of the thrown exception with greater freedom.

 

2. Error page

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title> Catch global exception </ title>
</head>
<body>
    <h1 style = "color: red"> An error occurred: </ h1>
    <div th:text="${url}"></div>
    <div th:text="${exception.message}"></div>
</body>
</html>

Description: The thymeleaf template is used here. This was introduced before: " SpringBoot Getting Started Series (4) Integrated Template Engine Thymeleaf "

 

3. Test class

Create a controller that tests abnormally

package com.weiz.controller;

import com.weiz.utils.JSONResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("err")
public class ErrorController {

    @RequestMapping("/error")
    public String error() {
        
        int a = 1 / 0;
        
        return "thymeleaf/error";
    }
    
    @RequestMapping("/ajaxerror")
    public String ajaxerror() {
        
        return "thymeleaf/ajaxerror";
    }
    
    @RequestMapping("/getAjaxerror")
    @ResponseBody
    public JSONResult getAjaxerror() {
        
        int a = 1 / 0;
        
        return JSONResult.ok();
    }
}

 

test

Type in the browser: http: // localhost: 8088 / err / error

 

 At last

This concludes the Spring Boot unified exception handling. Here only introduces the method of using @ControllerAdvice annotation to implement exception handling, and the implementation of ErrorController, you can go to understand.

The @ControllerAdvice method can only handle exceptions thrown by the controller, while the ErrorController-like method can handle all exceptions, including errors that have not entered the controller, such as 404, 401 and other errors.

 

Guess you like

Origin www.cnblogs.com/zhangweizhong/p/12600220.html