SpringBoot 统一异常处理

#1:主要是 `@ControllerAdvice`和ExceptionHandler两个注解,稍后会对连个注解进行解释!

 1 @Slf4j
 2 @ControllerAdvice
 3 public class ExceptionHandle {
 4 
 5     //记录系统异常
 6     private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
 7 
 8     /**
 9      * 1.@ExceptionHandler(ParamException.class) 声明了对 ParamException业务异常的处理,
10      * 并获取该业务异常中的错误提示,构造后返回给客户端。
11      * <p>
12      * 2.@ExceptionHandler(Exception.class) 声明了对 Exception 异常的处理,起到兜底作用,
13      * 不管 Controller 层执行的代码出现了什么未能考虑到的异常,都返回统一的错误提示给客户端。
14      */
15     @ExceptionHandler(value = Exception.class)
16     @ResponseBody
17     public BaseResponseData handle(Exception e) {
18         /* 判断异常对象*/
19         if (e instanceof BaseException) {
20             BaseException baseException = (BaseException) e;
21             log.error("异常类:" + this.getClass().getName());
22             log.error(baseException.getMessage());
23             return BaseResponseData.fail(baseException.getCode(), baseException.getMsg());
24         } else {
25             log.error("异常类:" + this.getClass().getName());
26             log.error(e.getMessage());
27             return BaseResponseData.fail(-1, "未知的异常");
28         }
29     }
30 }
View Code
 1 @Data
 2 public class BaseException extends RuntimeException {
 3 
 4     private static final long serialVersionUID = 1L;
 5     public static final int RESULT_FAIL = 0;
 6     public static final int RESULT_SUCCESS = 1;
 7 
 8     private Integer code;
 9     private String msg;
10     //返回对象
11     private Object data;
12 
13     public BaseException() {
14     }
15 
16     public BaseException(Integer code, String msg) {
17         super(msg);
18         this.code = code;
19         this.msg = msg;
20     }
21 
22     public BaseException(Integer code, String msg, Object object) {
23         this.code = code;
24         this.msg = msg;
25         this.data = object;
26     }
27 
28     public static BaseException success(Object data) {
29         return new BaseException(ResultCodeEnum.SUCCESS.getCode(), "ok", data);
30     }
31 
32     public static BaseException fail(Integer code, String message) {
33         return new BaseException(code, message, null);
34     }
35 }
View Code

 

posted on 2021-07-15 11:29  夜空中闪闪发光的星星  阅读(73)  评论(0)    收藏  举报