Spring @ControllerAdvice @ExceptionHandler 全局處理異常


對於與數據庫相關的 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 了!

一、優缺點

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

二、基本使用示例

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

@ControllerAdvice public class GlobalExceptionHandler { }

 

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

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

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

 

方法 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 層拋出的異常對象!

三、處理 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 給客戶端,更大的發揮空間需要按需求情況來做。

四、處理 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 層也不需要在手動記錄錯誤日志了。

五、總結

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

其實,被 @ExceptionHandler 注解的方法還可以聲明很多參數,詳見文檔。

@ControllerAdvice 也還可以結合 @InitBinder、@ModelAttribute 等注解一起使用,應用在所有被 @RequestMapping 注解的方法上,詳見搜索引擎。


免責聲明!

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



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