SpringBoot(6) SpringBoot配置全域性異常
1、全域性異常
@ControllerAdvice 如果是返回json資料 則用 RestControllerAdvice,就可以不加 @ResponseBody
//捕獲全域性異常,處理所有不可知的異常
@ExceptionHandler(value=Exception.class)
1 @RestControllerAdvice 2 public class CustomExtHandler { 3 4private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); 5 6 7//捕獲全域性異常,處理所有不可知的異常 8@ExceptionHandler(value=Exception.class) 9Object handleException(Exception e,HttpServletRequest request){ 10LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 11Map<String, Object> map = new HashMap<>(); 12map.put("code", 100); 13map.put("msg", e.getMessage()); 14map.put("url", request.getRequestURL()); 15return map; 16} 17 18 }
2、自定義異常型別
自定義異常型別MyException
1 /* 2* 功能描述: 建立自定義異常類 -- 繼承執行異常最高類 3* 4* */ 5 6 public class MyException extends RuntimeException{ 7 8public MyException(String code, String msg){ 9this.code = code; 10this.msg = msg; 11} 12 13private String code; 14private String msg; 15 16public String getCode() { 17return code; 18} 19public void setCode(String code) { 20this.code = code; 21} 22 23public String getMsg() { 24return msg; 25} 26 27public void setMsg(String msg) { 28this.msg = msg; 29} 30 31 }
修改CustomExtHandler
1 @RestControllerAdvice 2 public class CustomExtHandler { 3 4private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); 5 6 7//捕獲全域性異常,處理所有不可知的異常 8@ExceptionHandler(value=Exception.class) 9Object handleException(Exception e,HttpServletRequest request){ 10LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 11Map<String, Object> map = new HashMap<>(); 12map.put("code", 100); 13map.put("msg", e.getMessage()); 14map.put("url", request.getRequestURL()); 15return map; 16} 17 18/** 19* 功能描述: 處理自定義異常類 20* @return 21* 22*/ 23@ExceptionHandler(value = MyException.class) 24Object handleMyException(MyException e, HttpServletRequest request){ 25//進行頁面跳轉 26 //ModelAndView modelAndView = new ModelAndView(); 27 //modelAndView.setViewName("error.html"); 28 //modelAndView.addObject("msg", e.getMessage()); 29 //return modelAndView; 30 31//f返回json資料 32Map<String, Object> map = new HashMap<>(); 33map.put("code", e.getCode()); 34map.put("msg", e.getMessage()); 35map.put("url", request.getRequestURL()); 36return map; 37} 38 }
模擬一個異常實現頁面跳轉
1 /** 2* 功能描述: 模擬自定義異常 3* @return 4*/ 5 @RequestMapping(value = "/api/v1/myext") 6 public Object myext() { 7throw new MyException("500", "my ext異常"); 8 } 9
最後梳理順序:
首先,建立自定義異常類 MyException,繼承於RuntimeException。如果出異常,在@RestControllerAdvice註釋下的CustomExtHandler裡面捕獲,根據異常種類進行處理。
異常處理的官網地址: https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling