1.利用springmvc注解對Controller層異常全局處理
對於與數據庫相關的 Spring MVC 項目,我們通常會把 事務 配置在 Service層,當數據庫操作失敗時讓 Service 層拋出運行時異常,Spring 事物管理器就會進行回滾。
如此一來,我們的 Controller 層就不得不進行 try-catch Service 層的異常,否則會返回一些不友好的錯誤信息到客戶端。但是,Controller 層每個方法體都寫一些模板化的 try-catch 的代碼,很難看也難維護,特別是還需要對 Service 層的不同異常進行不同處理的時候。
1.1優缺點
- 優點:將Controller層的異常和數據校驗的異常進行統一異常處理,減少模板代碼,減少代碼量,提升擴展性和可維護性、
- 缺點:只能處理Controller層未捕獲(從Servcie層拋過來)的異常,對於Interceptor(攔截器)層的異常,Spring框架層的異常,就無能為力了。
1.2基本使用
1.2.1@ControllerAdvice 注解定義全局異常處理類
首先,確保此類GlobalExceptionHandler 能被掃描到並裝載進Spring容器中。
@ControllerAdvice public class GlobalExceptionHandler { }
1.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 層拋出的異常對象!
1.3處理Service層上拋的業務異常
1.3.1代碼示例
@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; } }
BusinessException屬於業務自定義異常類
@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); } }
這樣Controller層就不需要進行異常處理了;
有時我們會在復雜帶有數據庫事務的業務中,當出現不和預期的數據時,直接拋出封裝后的業務級運行時異常,進行數據庫事務回滾,並希望該異常信息能被返回顯示給用戶。
我們可以使用自定義異常類可以針對具體業務處理異常;
Logger 進行所有的異常日志記錄。
@ExceptionHandler(BusinessException.class) 聲明了對 BusinessException 業務異常的處理,並獲取該業務異常中的錯誤提示,構造后返回給客戶端。
@ExceptionHandler(Exception.class) 聲明了對 Exception 異常的處理,起到兜底作用,不管 Controller 層執行的代碼出現了什么未能考慮到的異常,都返回統一的錯誤提示給客戶端。
備注:以上 GlobalExceptionHandler 只是返回 Json 給客戶端,更大的發揮空間需要按需求情況來做。
但是實際開發中並不這么做,因為返回的Response對象可能封裝不同的數據,放在同一異常處理固然是方便,但是可能不實用;
1.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 層也不需要在手動記錄錯誤日志了。
其實,可以利用springaop進行攔截,然后記錄日志,詳情請看springaop【統一日志處理】相關文章。
1.5總結
其實,被 @ExceptionHandler 注解的方法還可以聲明很多參數,詳見文檔。
@ControllerAdvice 也還可以結合 @InitBinder、@ModelAttribute 等注解一起使用,應用在所有被 @RequestMapping 注解的方法上,詳見搜索引擎。
參考文章鏈接:
https://blog.csdn.net/kinginblue/article/details/70186586