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     }

 


免責聲明!

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



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