spring boot2.0+中添加全局异常捕获

1、添加自定义异常,继承RuntimeException,为什么继承RuntimeException呢?是因为我们的事务在RuntimeException异常下会发生回滚。

 1 public class BusinessException extends RuntimeException{
 2 
 3     public BusinessException(String code, String msg){
 4         this.code = code;
 5         this.msg = msg;
 6     }
 7 
 8     private String code;
 9     private String msg;
10 
11     public String getCode() {
12         return code;
13     }
14     public void setCode(String code) {
15         this.code = code;
16     }
17 
18     public String getMsg() {
19         return msg;
20     }
21 
22     public void setMsg(String msg) {
23         this.msg = msg;
24     }
25 
26 }
自定义异常类

2、添加全局异常捕获,使用@RestControllerAdvice 注解实现

 1 public class CustomExtHandler {
 2 
 3     private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
 4 
 5 
 6     //捕获全局异常,处理所有不可知的异常
 7     @ExceptionHandler(value=Exception.class)
 8     Object handleException(Exception e,HttpServletRequest request){
 9         LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
10         Map<String, Object> map = new HashMap<>();
11         map.put("code", 100);
12         map.put("msg", e.getMessage());
13         map.put("url", request.getRequestURL());
14         return map;
15     }
16 
17     /**
18      * 功能描述: 处理自定义异常类
19      * @return
20      *
21      */
22     @ExceptionHandler(value = BusinessException.class)
23     Object handleMyException(BusinessException e, HttpServletRequest request){
24         //f返回json数据
25         Map<String, Object> map = new HashMap<>();
26         map.put("code", e.getCode());
27         map.put("msg", e.getMsg());
28         map.put("url", request.getRequestURL());
29         return map;
30     }
全局异常捕获

3、使用

1 throw new BusinessException("200","出错了啊!");

猜你喜欢

转载自www.cnblogs.com/rolayblog/p/11237259.html