springboot 统一异常处理

思路:

1、定义自己的业务异常

2、用异常拦截(@ControllerAdvice 和 @ExceptionHandler)对返回结果进行处理

@ControllerAdvice:控制器增前器,使@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。

@ExceptionHandler:异常处理器,对指定异常进行处理。

@RestControllerAdvice:@ControllerAdvice + @ResponseBody

@ControllerAdvice原理篇:https://blog.csdn.net/andy_zhang2007/article/details/100041219

 

实现:

1、定义自定义的业务异常(目前只是定义了一个最简单的)

public class BussinessException extends RuntimeException{
    public BussinessException(String message) {
        super(message);
    }
}

 

2、定义全局异常拦截

@ControllerAdvice
public class GlobalExcption {
    @ExceptionHandler(BussinessException.class)
//    @ResponseStatus 可以定义返回code和message
//    @ResponseStatus(code = HttpStatus.BAD_REQUEST,value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String globalExcptionDeal(BussinessException e){
        return "BussinessException: " + e.getMessage();
    }
}

这是一个最基本的定义:

  • @ControllerAdvice + @ResponseBody 可以用 @RestControllerAdvice 代替
  • 可以用 @ResponseStatus 返回状态码和消息

 

3、抛出异常

    @RequestMapping("/bb")
    @ResponseBody
    public String bb() {
        throw new BussinessException("自定义异常1");
    }

注意:

  • 这个异常只有在controller层并且抛出去之后(不能自行try catch)才能被拦截到。

 

posted @ 2020-03-27 10:57  张小戳的夏天  阅读(115)  评论(0)    收藏  举报