When an exception or request error occurs on the back end, the front end usually displays the following:

This article focuses on unified exception handling in SpringBoot:

First: use the @ControllerAdvice and @ExceptionHandler annotations

Second: Implement the ErrorController interface

  • The first: With the @ControllerAdvice and @ExceptionHandler annotations, @ControllerAdvice is a Controller enhanced class that will be blocked when an exception occurs in the Controller layer that matches the exception class defined in the Controller layer. Default exception handling methods or custom exception handling classes are used

    @Slf4j
    @RestControllerAdvice
    public class InternalExceptionHandler {
    
        @ExceptionHandler(Exception.class)
        public Result internalException(HttpServletResponse response,Exception e){
            Result result = new Result(response.getStatus(), "Exception thrown by Controller layer", e.getMessage());
    
            returnresult; }}Copy the code
  • The second is to implement the ErrorController interface. The default error handling class of the system is BasicErrorController, and the above error page will be displayed. Writing your own error handling class, the default above will not work and getErrorPath() will redirect to the Controller handling the exception

    @RestController
    public class HttpErrorHandler implements ErrorController {
    
        private static final String ERROR_PATH="/error";
        
        @RequestMapping(value = ERROR_PATH)
        public Result error(HttpServletResponse response,Exception e) {
            Result result = new Result(response.getStatus(), "Global exception", e.getMessage());
            return result;
        }
    
        @Override
        public String getErrorPath(a) {
            returnERROR_PATH; }}Copy the code

Testing:

@RestController
@RequestMapping
public class HelloConroller {
    
    @GetMapping("/getMsg")
    public String say(a){

        int a=10/0;

        return "Successful execution!"; }}Copy the code