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

posted on 2019-03-05 11:07 【cosmo】 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值