springMVC 统一异常处理

SpringMVC异常处理注解@ExceptionHandler

关于@ExceptionHandler注解不详细说明,次记录仅供参考,直接贴项目中的代码用法,不喜勿喷,不足之处请指点。

Controller:

1.controller继承异常基类BaseController 

 1 public class BaseController {
 2     
 3     protected Logger logger = LoggerFactory.getLogger(getClass());
 4         
 5     @ExceptionHandler
 6     public @ResponseBody Object exceptionHandler(Exception exception, HttpServletResponse response) {
 7         if (exception instanceof BException) {
 8             exception.printStackTrace();
 9             logger.error(exception.getMessage());
10             return JsonResult.error(((BException) exception).getMsg());
11         }else {
12             exception.printStackTrace();
13             logger.error(exception.getMessage());
14             return JsonResult.error("系统发生错误。");
15         }
16     }
17 
18 }

BException:

2.自定义异常BException,继承RuntimeException

 1 public class BException extends RuntimeException{
 2     private static final long serialVersionUID = 1L;
 3     private String msg;//错误消息
 4     private boolean async; //是否异步
 5     
 6     public BException(){
 7         super();
 8     }
 9     
10     public BException(String msg) {
11         super(msg);
12         this.async = false;
13         this.msg = msg;
14     }
15     
16     public BException(Exception e){
17         super(e.getMessage());
18         this.async = false;
19         if(e instanceof BException){
20             BException self = (BException) e;
21            this.msg = self.getMsg();
22         }else{
23             this.msg = e.getMessage();
24         }
25         
26     }
27 
28     public String getMsg() {
29         return msg;
30     }
31 
32     public void setMsg(String msg) {
33         this.msg = msg;
34     }
35 
36     public boolean isAsync() {
37         return async;
38     }
39 
40     public void setAsync(boolean async) {
41         this.async = async;
42     }
43 }

Service:

3.在service层直接使用自定义的异常类,将异常抛出到controller,因为controller继承异常基类BaseController ,所以service中相关的异常BaseController会处理

1     public Map<String, Object> findRank(String account) throws BException{
2         List<Map<String, Object>> list = dao.findRank(account);
3         if(list == null || list.isEmpty())
4             throw new BException("未找到再生值排名");
5         
6         Map<String, Object> map = list.get(0);
7         return map;
8     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值