Spring/SpringBoot unified exception handling @RestControllerAdvice (ExceptionHandleAdvice)

In the project, it is impossible for us to predict and catch all exceptions. In order to avoid unexpected exceptions being thrown to the client, Spring provides us with a unified exception handling mechanism @RestControllerAdvice, which allows us to handle exceptions when logic throws exceptions. Make exceptions friendly or specify the returned data structure to the front end.
Usage examples are as follows:

@RestControllerAdvice
public class ExceptionHandleAdvice {
    
    
    private  final Logger logger = LoggerFactory.getLogger(ExceptionHandleAdvice.class);

    @ExceptionHandler(Exception.class)
    public String exceptionHandle(Exception e){
    
    
        logger.error("系统异常:", e);
        return "系统异常!";
    }
}

If the above code is placed in the Spring project, exceptions thrown in the Controller will be centrally processed here, and "System exception!" will be returned to the user after printing the log.
Write a Controller example to experience the difference between before and after use:

@RestController
@RequestMapping("/time")
public class TimeController {
    
    

    @GetMapping("/now")
    public LocalDateTime now(){
    
    
        return LocalDateTime.now();
    }

    /**
     * 返回当前时间+count后的时间字符串
     * 
     * @param count 未来天数
     * @return 时间字符串
     */
    @GetMapping("/oneDay")
    public LocalDateTime now(@RequestParam Long count){
    
    
        return LocalDateTime.now().plusDays(count);
    }
}

This is a very simple controller, which returns the time string after the current time + count. We only need to use the get request to pass the count to the server, and then the server will return the time string after the current time + count days.
Test the browser:
normal time
Of course, the vulnerability of this interface is also obvious. When we pass a count value that is not a Long type, an exception will appear: a
Exception request
very unfriendly exception error message. People who have never learned programming will think that there is something wrong with their computer. . So we need to be more user-friendly and add the ExceptionHandleAdvice unified exception handling class written above to start it again and try it again:
Handled exception
very friendly

This usage is just a small instance of @RestControllerAdvice. We can add other logic to this unified exception handling class such as:

@RestControllerAdvice
public class ExceptionHandleAdvice {
    
    
    private  final Logger logger = LoggerFactory.getLogger(ExceptionHandleAdvice.class);

    @ExceptionHandler(Exception.class)
    public String exceptionHandle(Exception e) {
    
    
        logger.error("系统异常:", e);
        return "系统异常!";
    }
    // 处理自定义异常
    @ExceptionHandler(TermException.class)
    public String exceptionHandle(TermException termException) {
    
    
        logger.error("自定义异常:", termException);
        return termException.getMessage();
    }

    // 处理正常请求,对时间进行格式化
    @ResponseStatus(HttpStatus.ACCEPTED) // 值为202
    public <T> String sendSuccessResponse(T data) {
    
    
        if (data instanceof LocalDateTime) {
    
    

            return "时间为" + ((LocalDateTime) data).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        return data.toString();
    }
}

When your Controller throws your custom exception TermException, it will be caught by the second method above and the message will be returned to the user. Test it:
first throw the exception in the controller:

   @GetMapping("/oneDay")
   public LocalDateTime now(@RequestParam Long count){
    
    
       if (count < 0L){
    
    
           throw new TermException("count不能小于0!");
       }
       return LocalDateTime.now().plusDays(count);
   }

After restarting the service, the results after the request are as follows:
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41674401/article/details/121643986