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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM