spring boot全局统一异常处理

自定义异常

 1 /**
 2  * 自定义异常
 3  * @author Holley
 4  * @create 2018-05-24 14:39
 5  **/
 6 public class SelectNoFindException extends RuntimeException{
 7     /**
 8      * 异常代码
 9      */
10     private Integer code;
11     /**
12      * 自定义错误信息
13      */
14     private String erromessage;
15 
16     public SelectNoFindException(String erromessage ,String message){
17         super(message);
18         this.erromessage = erromessage;
19     }
20 
21     public Integer getCode() {
22         return code;
23     }
24     public String getErromessage() {
25         return erromessage;
26     }
27     public void setCode(Integer code) {
28         this.code = code;
29     }
30     public void setErromessage(String erromessage) {
31         this.erromessage = erromessage;
32     }
33 
34 }
View Code

serviceimpl层代码

public List<Saler> listSalerContact(Long cid) {
        List<Saler> listSaler = null;
        try {
            listSaler = salerDAO.listSalerContact(cid);
        }catch (Exception e){
            e.printStackTrace();
            throw new  SelectNoFindException("获取订货商列表失败!!",e.getMessage());
        }
        return listSaler;
    }
View Code

全局统一异常处理代码

 1 /**
 2  * 全局统一异常处理
 3  * @author Holley
 4  * @create 2018-05-24 14:59
 5  **/
 6 @RestControllerAdvice
 7 public class GlobalExceptionHandler {
 8     private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 9 
10     @ExceptionHandler(value = Exception.class)
11     public Response handler(Exception e){
12         Response r = new Response();
13         if (e instanceof SelectNoFindException){
14             SelectNoFindException selectNoFindException = (SelectNoFindException) e;
15             r.setMessage(selectNoFindException.getErromessage());
16             r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
17             log.error(selectNoFindException.getMessage());
18             return r;
19         } else {
20             r.setCode(WhiteListConstant.RESPONSE_CODE_FAIL);
21             r.setMessage("系统错误");
22             log.error(e.getMessage());
23             return r;
24         }
25     }
26 }
View Code

猜你喜欢

转载自www.cnblogs.com/zhlblogs/p/9084270.html