統一異常處理@RestContrllerAdvice,@ExceptionHandler(轉載)

思想很重要javascript

統一異常處理實現方式:使用註解@RestContrllerAdvice,@ExceptionHandlerhtml

先想明白一個問題:定義統一異常處理類以後,是否是在Contrller中就不用捕獲異常了。若是出現異常,都會被統一異常處理類處理掉。仍是統一異常處理類,只是Controer捕獲異常補充,Contrller捕獲不到了,它來填補漏洞。java

下面轉載的一篇文章很不錯git

http://blog.csdn.net/kinginblue/article/details/70186586github

關鍵詞:業務異常,未知異常,參數異常(註解方式),Controller分離(統一處理Controller只負責處理異常,原來Controller負責處理業務邏輯)web

另外關於統一異常處理的其餘思路:spring

1,http://blog.csdn.net/nmgrd/article/details/57080248  定義統一處理異常類,普通Controller用全部普通Controller繼承統一異常處理類。數據庫

 2,Aop實現異常處理  express

 https://www.cnblogs.com/ssslinppp/p/7606038.htmlapi

        @ControllerAdvice + @ExceptionHandler 全局處理 Controller 層異常                                                  

 

零、前言

對於與數據庫相關的 Spring MVC 項目,咱們一般會把 事務 配置在 Service層,當數據庫操做失敗時讓 Service 層拋出運行時異常,Spring 事物管理器就會進行回滾。

如此一來,咱們的 Controller 層就不得不進行 try-catch Service 層的異常,不然會返回一些不友好的錯誤信息到客戶端。可是,Controller 層每一個方法體都寫一些模板化的 try-catch 的代碼,很難看也難維護,特別是還須要對 Service 層的不一樣異常進行不一樣處理的時候。例如如下 Controller 方法代碼(很是難看且冗餘):

/** * 手動處理 Service 層異常和數據校驗異常的示例 * @param dog * @param errors * @return */ @PostMapping(value = "") AppResponse add(@Validated(Add.class) @RequestBody Dog dog, Errors errors){ AppResponse resp = new AppResponse(); try { // 數據校驗 BSUtil.controllerValidate(errors); // 執行業務 Dog newDog = dogService.save(dog); // 返回數據 resp.setData(newDog); }catch (BusinessException e){ LOGGER.error(e.getMessage(), e); resp.setFail(e.getMessage()); }catch (Exception e){ LOGGER.error(e.getMessage(), e); resp.setFail("操做失敗!"); } return resp; }

本文講解使用 @ControllerAdvice + @ExceptionHandler 進行全局的 Controller 層異常處理,只要設計得當,就不再用在 Controller 層進行 try-catch 了!並且,@Validated 校驗器註解的異常,也能夠一塊兒處理,無需手動判斷綁定校驗結果 BindingResult/Errors 了!

1、優缺點

  • 優勢:將 Controller 層的異常和數據校驗的異常進行統一處理,減小模板代碼,減小編碼量,提高擴展性和可維護性。
  • 缺點:只能處理 Controller 層未捕獲(往外拋)的異常,對於 Interceptor(攔截器)層的異常,Spring 框架層的異常,就無能爲力了。

2、基本使用示例

2.1 @ControllerAdvice 註解定義全局異常處理類

@ControllerAdvice public class GlobalExceptionHandler { }
  • 1
  • 2
  • 3

請確保此 GlobalExceptionHandler 類能被掃描到並裝載進 Spring 容器中。

2.2 @ExceptionHandler 註解聲明異常處理方法

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody String handleException(){ return "Exception Deal!"; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

方法 handleException() 就會處理全部 Controller 層拋出的 Exception 及其子類的異常,這是最基本的用法了。

@ExceptionHandler 註解的方法的參數列表裏,還能夠聲明不少種類型的參數,詳見文檔。其原型以下:

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ExceptionHandler { /** * Exceptions handled by the annotated method. If empty, will default to any * exceptions listed in the method argument list. */ Class<? extends Throwable>[] value() default {}; }

若是 @ExceptionHandler 註解中未聲明要處理的異常類型,則默認爲參數列表中的異常類型。因此上面的寫法,還能夠寫成這樣:

@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler() @ResponseBody String handleException(Exception e){ return "Exception Deal! " + e.getMessage(); } }

 

參數對象就是 Controller 層拋出的異常對象!

3、處理 Service 層上拋的業務異常

有時咱們會在複雜的帶有數據庫事務的業務中,當出現不和預期的數據時,直接拋出封裝後的業務級運行時異常,進行數據庫事務回滾,並但願該異常信息能被返回顯示給用戶。

3.1 代碼示例

封裝的業務異常類:

public class BusinessException extends RuntimeException { public BusinessException(String message){ super(message); } }

 

Service 實現類:

@Service public class DogService { @Transactional public Dog update(Dog dog){ // some database options // 模擬狗狗新名字與其餘狗狗的名字衝突 BSUtil.isTrue(false, "狗狗名字已經被使用了..."); // update database dog info return dog; } }

 

其中輔助工具類 BSUtil

public static void isTrue(boolean expression, String error){ if(!expression) { throw new BusinessException(error); } }

 

那麼,咱們應該在 GlobalExceptionHandler 類中聲明該業務異常類,並進行相應的處理,而後返回給用戶。更貼近真實項目的代碼,應該長這樣子:

/** * Created by kinginblue on 2017/4/10. * @ControllerAdvice + @ExceptionHandler 實現全局的 Controller 層的異常處理 */ @ControllerAdvice public class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 處理全部不可知的異常 * @param e * @return */ @ExceptionHandler(Exception.class) @ResponseBody AppResponse handleException(Exception e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail("操做失敗!"); return response; } /** * 處理全部業務異常 * @param e * @return */ @ExceptionHandler(BusinessException.class) @ResponseBody AppResponse handleBusinessException(BusinessException e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail(e.getMessage()); return response; } }

 

Controller 層的代碼,就不須要進行異常處理了:

@RestController @RequestMapping(value = "/dogs", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE}) public class DogController { @Autowired private DogService dogService; @PatchMapping(value = "") Dog update(@Validated(Update.class) @RequestBody Dog dog){ return dogService.update(dog); } }

 

3.2 代碼說明

Logger 進行全部的異常日誌記錄。

@ExceptionHandler(BusinessException.class) 聲明瞭對 BusinessException 業務異常的處理,並獲取該業務異常中的錯誤提示,構造後返回給客戶端。

@ExceptionHandler(Exception.class) 聲明瞭對 Exception 異常的處理,起到兜底做用,無論 Controller 層執行的代碼出現了什麼未能考慮到的異常,都返回統一的錯誤提示給客戶端。

備註:以上 GlobalExceptionHandler 只是返回 Json 給客戶端,更大的發揮空間須要按需求狀況來作。

4、處理 Controller 數據綁定、數據校驗的異常

在 Dog 類中的字段上的註解數據校驗規則:

@Data public class Dog { @NotNull(message = "{Dog.id.non}", groups = {Update.class}) @Min(value = 1, message = "{Dog.age.lt1}", groups = {Update.class}) private Long id; @NotBlank(message = "{Dog.name.non}", groups = {Add.class, Update.class}) private String name; @Min(value = 1, message = "{Dog.age.lt1}", groups = {Add.class, Update.class}) private Integer age; }

 

說明:@NotNull、@Min、@NotBlank 這些註解的使用方法,不在本文範圍內。若是不熟悉,請查找資料學習便可。

其餘說明:
@Data 註解是 **Lombok** 項目的註解,可使咱們不用再在代碼裏手動加 getter & setter。
在 Eclipse 和 IntelliJ IDEA 中使用時,還須要安裝相關插件,這個步驟自行Google/Baidu 吧!

Lombok 使用方法見:Java奇淫巧技之Lombok

SpringMVC 中對於 RESTFUL 的 Json 接口來講,數據綁定和校驗,是這樣的:

/** * 使用 GlobalExceptionHandler 全局處理 Controller 層異常的示例 * @param dog * @return */ @PatchMapping(value = "") AppResponse update(@Validated(Update.class) @RequestBody Dog dog){ AppResponse resp = new AppResponse(); // 執行業務 Dog newDog = dogService.update(dog); // 返回數據 resp.setData(newDog); return resp; }

使用 @Validated + @RequestBody 註解實現。

當使用了 @Validated + @RequestBody 註解可是沒有在綁定的數據對象後面跟上 Errors 類型的參數聲明的話,Spring MVC 框架會拋出 MethodArgumentNotValidException 異常。

因此,在 GlobalExceptionHandler 中加上對 MethodArgumentNotValidException 異常的聲明和處理,就能夠全局處理數據校驗的異常了!加完後的代碼以下:

/** * Created by kinginblue on 2017/4/10. * @ControllerAdvice + @ExceptionHandler 實現全局的 Controller 層的異常處理 */ @ControllerAdvice public class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 處理全部不可知的異常 * @param e * @return */ @ExceptionHandler(Exception.class) @ResponseBody AppResponse handleException(Exception e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail("操做失敗!"); return response; } /** * 處理全部業務異常 * @param e * @return */ @ExceptionHandler(BusinessException.class) @ResponseBody AppResponse handleBusinessException(BusinessException e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail(e.getMessage()); return response; } /** * 處理全部接口數據驗證異常 * @param e * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody AppResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage()); return response; } }

注意到了嗎,全部的 Controller 層的異常的日誌記錄,都是在這個 GlobalExceptionHandler 中進行記錄。也就是說,Controller 層也不須要在手動記錄錯誤日誌了。

5、總結

本文主要講 @ControllerAdvice + @ExceptionHandler 組合進行的 Controller 層上拋的異常全局統一處理。

其實,被 @ExceptionHandler 註解的方法還能夠聲明不少參數,詳見文檔。

@ControllerAdvice 也還能夠結合 @InitBinder、@ModelAttribute 等註解一塊兒使用,應用在全部被 @RequestMapping 註解的方法上,詳見搜索引擎。

6、附錄

本文示例代碼已放到 Github

相關文章
相關標籤/搜索