spring boot 攔截異常 統一處理


spring boot 默認情況下會映射到 /error 進行異常處理,提示不友好,需要自定義異常處理,提供友好展示

1.自定義異常類(spring 對於 RuntimeException 異常才會進行事務回滾):

 1 package com.zpark.tools.exception;
 3 /**
 4  * @author cosmo
 5  * @Title: CommonException
 6  * @ProjectName  
 7  * @Description:  
 8  * @date  
 9  */
10 public class CommonException extends RuntimeException{
11 
12     private String rerutnCode;
13 
14     private String errorMsg;
15 
16     public CommonException(String returnCode ,String errorMsg){
17         this.returnCode = returnCode;
18         this.errorMsg = errorMsg;
19     }
20 
21     public String getReturnCode() {
22         return returnCode;
23     }
24 
25     public void setReturnCode(String returnCode) {
26         this.returnCode = returnCode;
27     }
28 
29     public String getErrorMsg() {
30         return errorMsg;
31     }
32 
33     public void setErrorMsg(String errorMsg) {
34         this.errorMsg = errorMsg;
35     }
36 }

2.定義全局異常類:

 1 package com.zpark.tools.exception;
 2 
 3 import com.zpark.tools.Constants;
 4 import org.slf4j.Logger;
 5 import org.slf4j.LoggerFactory;
 6 import org.springframework.web.bind.annotation.ControllerAdvice;
 7 import org.springframework.web.bind.annotation.ExceptionHandler;
 8 import org.springframework.web.bind.annotation.ResponseBody;
10 import javax.servlet.http.HttpServletRequest;
11 import java.util.HashMap;
12 import java.util.Map;
13 
14 /**
15  * @author cosmo
16  * @Title: CommonExceptionHandler
17  * @ProjectName  
18  * @Description:  
19  * @date  
20  */
21 @ControllerAdvice
22 public class CommonExceptionAdvice {
23 
24     private Logger log = LoggerFactory.getLogger(CommonExceptionAdvice.class);
25     /**
26      * 全局異常捕捉處理
27      * @param ex
28      * @return
29      */
30     @ResponseBody
31     @ExceptionHandler(value = Exception.class)
32     public Map errorHandler(HttpServletRequest request,Exception ex) {34         Map map = new HashMap();
35         map.put("retrnCode", 100);
36         map.put("errorMsg", ex.getMessage());51         return map;
52     }67 }

運行中出現異常,會返回報錯信息和錯誤code


免責聲明!

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



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