1 【SpringMVC學習07】SpringMVC中的統一異常處理
我們知道,系統中異常包括:編譯時異常和運行時異常RuntimeException,前者通過捕獲異常從而獲取異常信息,后者主要通過規范代碼開發、測試通過手段減少運行時異常的發生。在開發中,不管是dao層、service層還是controller層,都有可能拋出異常,在springmvc中,能將所有類型的異常處理從各處理過程解耦出來,既保證了相關處理過程的功能較單一,也實現了異常信息的統一處理和維護。這篇博文主要總結一下SpringMVC中如何統一處理異常。
1. 異常處理思路
首先來看一下在springmvc中,異常處理的思路(我已盡力畫好看點了,不要噴我~):
如上圖所示,系統的dao、service、controller出現異常都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進行異常處理。springmvc提供全局異常處理器(一個系統只有一個異常處理器)進行統一異常處理。明白了springmvc中的異常處理機制,下面就開始分析springmvc中的異常處理。
2. springmvc中自帶的簡單異常處理器
springmvc中自帶了一個異常處理器叫SimpleMappingExceptionResolver,該處理器實現了HandlerExceptionResolver 接口,全局異常處理器都需要實現該接口。我們要使用這個自帶的異常處理器,首先得在springmvc.xml文件中配置該處理器:
<!-- springmvc提供的簡單異常處理器 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!-- 定義默認的異常處理頁面 --> <property name="defaultErrorView" value="/WEB-INF/jsp/error.jsp"/> <!-- 定義異常處理頁面用來獲取異常信息的變量名,也可不定義,默認名為exception --> <property name="exceptionAttribute" value="ex"/> <!-- 定義需要特殊處理的異常,這是重要點 --> <property name="exceptionMappings"> <props> <prop key="ssm.exception.CustomException">/WEB-INF/jsp/custom_error.jsp</prop> </props> <!-- 還可以定義其他的自定義異常 --> </property> </bean>
從上面的配置來看,最重要的是要配置特殊處理的異常,這些異常一般都是我們自定義的,根據實際情況來自定義的異常,然后也會跳轉到不同的錯誤顯示頁面顯示不同的錯誤信息。這里就用一個自定義異常CustomException來說明問題,定義如下:
//定義一個簡單的異常類 public class CustomException extends Exception { //異常信息 public String message; public CustomException(String message) { super(message); this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
接下來就是寫測試程序了,還是使用查詢的例子,如下:
然后我們在前台輸入url來測試:http://localhost:8080/SpringMVC_Study/editItems.action?id=11,故意傳一個id為11,我的數據庫中沒有id為11的項,所以肯定查不到,反正讓它查不到即可。這樣它就會拋出自定義的異常,然后被上面配置的全局異常處理器捕獲並執行,跳轉到我們指定的頁面,然后顯示一下該商品不存在即可。所以這個流程是很清晰的。
從上面的過程可知,使用SimpleMappingExceptionResolver進行異常處理,具有集成簡單、有良好的擴展性(可以任意增加自定義的異常和異常顯示頁面)、對已有代碼沒有入侵性等優點,但該方法僅能獲取到異常信息,若在出現異常時,對需要獲取除異常以外的數據的情況不適用。
3. 自定義全局異常處理器
全局異常處理器處理思路:
- 解析出異常類型
- 如果該異常類型是系統自定義的異常,直接取出異常信息,在錯誤頁面展示
- 如果該異常類型不是系統自定義的異常,構造一個自定義的異常類型(信息為“未知錯誤”)
springmvc提供一個HandlerExceptionResolver接口,自定義全局異常處理器必須要實現這個接口,如下:
public class CustomExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ex.printStackTrace(); CustomException customException = null; //如果拋出的是系統自定義的異常則直接轉換 if(ex instanceof CustomException) { customException = (CustomException) ex; } else { //如果拋出的不是系統自定義的異常則重新構造一個未知錯誤異常 //這里我就也有CustomException省事了,實際中應該要再定義一個新的異常 customException = new CustomException("系統未知錯誤"); } //向前台返回錯誤信息 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", customException.getMessage()); modelAndView.setViewName("/WEB-INF/jsp/error.jsp"); return modelAndView; } }
全局異常處理器中的邏輯很清楚,我就不再多說了,然后就是在springmvc.xml中配置這個自定義的異常處理器:
<!-- 自定義的全局異常處理器 只要實現HandlerExceptionResolver接口就是全局異常處理器--> <bean class="ssm.exception.CustomExceptionResolver"></bean>
然后就可以使用上面那個測試用例再次測試了。可以看出在自定義的異常處理器中能獲取導致出現異常的對象,有利於提供更詳細的異常處理信息。一般用這種自定義的全局異常處理器比較多。
4. @ExceptionHandler注解實現異常處理
還有一種是使用注解的方法,我大概說一下思路,因為這種方法對代碼的入侵性比較大,我不太喜歡用這種方法。
首先寫個BaseController類,並在類中使用@ExceptionHandler注解聲明異常處理的方法,如:
public class BaseController { @ExceptionHandler public String exp(HttpServletRequest request, Exception ex) { //異常處理 //...... } }
然后將所有需要異常處理的Controller都繼承這個BaseController,雖然從執行來看,不需要配置什么東西,但是代碼有侵入性,需要異常處理的Controller都要繼承它才行。
關於springmvc的異常處理,就總結這么多吧。
2 Spring MVC異常統一處理的三種方式
正文
Spring 統一異常處理有 3 種方式,分別為:
- 使用 @ ExceptionHandler 注解
- 實現 HandlerExceptionResolver 接口
- 使用 @controlleradvice 注解
使用 @ ExceptionHandler 注解
使用該注解有一個不好的地方就是:進行異常處理的方法必須與出錯的方法在同一個Controller里面。使用如下:
1 @Controller 2 public class GlobalController { 3 4 /** 5 * 用於處理異常的 6 * @return 7 */ 8 @ExceptionHandler({MyException.class}) 9 public String exception(MyException e) { 10 System.out.println(e.getMessage()); 11 e.printStackTrace(); 12 return "exception"; 13 } 14 15 @RequestMapping("test") 16 public void test() { 17 throw new MyException("出錯了!"); 18 } 19 }
可以看到,這種方式最大的缺陷就是不能全局控制異常。每個類都要寫一遍。
實現 HandlerExceptionResolver 接口
這種方式可以進行全局的異常控制。例如:
1 @Component 2 public class ExceptionTest implements HandlerExceptionResolver{ 3 4 /** 5 * TODO 簡單描述該方法的實現功能(可選). 6 * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) 7 */ 8 public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, 9 Exception ex) { 10 System.out.println("This is exception handler method!"); 11 return null; 12 } 13 }
使用 @ControllerAdvice+ @ ExceptionHandler 注解
上文說到 @ ExceptionHandler 需要進行異常處理的方法必須與出錯的方法在同一個Controller里面。那么當代碼加入了 @ControllerAdvice,則不需要必須在同一個 controller 中了。這也是 Spring 3.2 帶來的新特性。從名字上可以看出大體意思是控制器增強。 也就是說,@controlleradvice + @ ExceptionHandler 也可以實現全局的異常捕捉。
請確保此WebExceptionHandle 類能被掃描到並裝載進 Spring 容器中。
1 @ControllerAdvice 2 @ResponseBody 3 public class WebExceptionHandle { 4 private static Logger logger = LoggerFactory.getLogger(WebExceptionHandle.class); 5 /** 6 * 400 - Bad Request 7 */ 8 @ResponseStatus(HttpStatus.BAD_REQUEST) 9 @ExceptionHandler(HttpMessageNotReadableException.class) 10 public ServiceResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) { 11 logger.error("參數解析失敗", e); 12 return ServiceResponseHandle.failed("could_not_read_json"); 13 } 14 15 /** 16 * 405 - Method Not Allowed 17 */ 18 @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) 19 @ExceptionHandler(HttpRequestMethodNotSupportedException.class) 20 public ServiceResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { 21 logger.error("不支持當前請求方法", e); 22 return ServiceResponseHandle.failed("request_method_not_supported"); 23 } 24 25 /** 26 * 415 - Unsupported Media Type 27 */ 28 @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) 29 @ExceptionHandler(HttpMediaTypeNotSupportedException.class) 30 public ServiceResponse handleHttpMediaTypeNotSupportedException(Exception e) { 31 logger.error("不支持當前媒體類型", e); 32 return ServiceResponseHandle.failed("content_type_not_supported"); 33 } 34 35 /** 36 * 500 - Internal Server Error 37 */ 38 @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 39 @ExceptionHandler(Exception.class) 40 public ServiceResponse handleException(Exception e) { 41 if (e instanceof BusinessException){ 42 return ServiceResponseHandle.failed("BUSINESS_ERROR", e.getMessage()); 43 } 44 45 logger.error("服務運行異常", e); 46 e.printStackTrace(); 47 return ServiceResponseHandle.failed("server_error"); 48 } 49 }
如果 @ExceptionHandler 注解中未聲明要處理的異常類型,則默認為參數列表中的異常類型。所以還可以寫成這樣:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler() @ResponseBody String handleException(Exception e){ return "Exception Deal! " + e.getMessage(); } }
參數對象就是 Controller 層拋出的異常對象!
繼承 ResponseEntityExceptionHandler 類來實現針對 Rest 接口 的全局異常捕獲,並且可以返回自定義格式:
1 @Slf4j 2 @ControllerAdvice 3 public class ExceptionHandlerBean extends ResponseEntityExceptionHandler { 4 5 /** 6 * 數據找不到異常 7 * @param ex 8 * @param request 9 * @return 10 * @throws IOException 11 */ 12 @ExceptionHandler({DataNotFoundException.class}) 13 public ResponseEntity<Object> handleDataNotFoundException(RuntimeException ex, WebRequest request) throws IOException { 14 return getResponseEntity(ex,request,ReturnStatusCode.DataNotFoundException); 15 } 16 17 /** 18 * 根據各種異常構建 ResponseEntity 實體. 服務於以上各種異常 19 * @param ex 20 * @param request 21 * @param specificException 22 * @return 23 */ 24 private ResponseEntity<Object> getResponseEntity(RuntimeException ex, WebRequest request, ReturnStatusCode specificException) { 25 26 ReturnTemplate returnTemplate = new ReturnTemplate(); 27 returnTemplate.setStatusCode(specificException); 28 returnTemplate.setErrorMsg(ex.getMessage()); 29 30 return handleExceptionInternal(ex, returnTemplate, 31 new HttpHeaders(), HttpStatus.OK, request); 32 } 33 34 }
以上就是 Spring 處理程序統一異常的三種方式。
3 @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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
本文講解使用 @ControllerAdvice + @ExceptionHandler 進行全局的 Controller 層異常處理,只要設計得當,就再也不用在 Controller 層進行 try-catch 了!而且,@Validated 校驗器注解的異常,也可以一起處理,無需手動判斷綁定校驗結果 BindingResult/Errors 了!
一、優缺點
優點:將 Controller 層的異常和數據校驗的異常進行統一處理,減少模板代碼,減少編碼量,提升擴展性和可維護性。
缺點:只能處理 Controller 層未捕獲(往外拋)的異常,對於 Interceptor(攔截器)層的異常,Spring 框架層的異常,就無能為力了。
二、基本使用示例
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 {};
}
1
2
3
4
5
6
7
8
9
10
11
12
如果 @ExceptionHandler 注解中未聲明要處理的異常類型,則默認為參數列表中的異常類型。所以上面的寫法,還可以寫成這樣:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler()
@ResponseBody
String handleException(Exception e){
return "Exception Deal! " + e.getMessage();
}
}
1
2
3
4
5
6
7
8
9
參數對象就是 Controller 層拋出的異常對象!
三、處理 Service 層上拋的業務異常
有時我們會在復雜的帶有數據庫事務的業務中,當出現不和預期的數據時,直接拋出封裝后的業務級運行時異常,進行數據庫事務回滾,並希望該異常信息能被返回顯示給用戶。
3.1 代碼示例
封裝的業務異常類:
public class BusinessException extends RuntimeException {
public BusinessException(String message){
super(message);
}
}
1
2
3
4
5
6
Service 實現類:
@Service
public class DogService {
@Transactional
public Dog update(Dog dog){
// some database options
// 模擬狗狗新名字與其他狗狗的名字沖突
BSUtil.isTrue(false, "狗狗名字已經被使用了...");
// update database dog info
return dog;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
其中輔助工具類 BSUtil
public static void isTrue(boolean expression, String error){
if(!expression) {
throw new BusinessException(error);
}
}
1
2
3
4
5
那么,我們應該在 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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
說明:@NotNull、@Min、@NotBlank 這些注解的使用方法,不在本文范圍內。如果不熟悉,請查找資料學習即可。
其他說明:
@Data 注解是 **Lombok** 項目的注解,可以使我們不用再在代碼里手動加 getter & setter。
在 Eclipse 和 IntelliJ IDEA 中使用時,還需要安裝相關插件,這個步驟自行Google/Baidu 吧!
1
2
3
4
5
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
使用 @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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
注意到了嗎,所有的 Controller 層的異常的日志記錄,都是在這個 GlobalExceptionHandler 中進行記錄。也就是說,Controller 層也不需要在手動記錄錯誤日志了。
五、總結
本文主要講 @ControllerAdvice + @ExceptionHandler 組合進行的 Controller 層上拋的異常全局統一處理。
其實,被 @ExceptionHandler 注解的方法還可以聲明很多參數,詳見文檔。
@ControllerAdvice 也還可以結合 @InitBinder、@ModelAttribute 等注解一起使用,應用在所有被 @RequestMapping 注解的方法上,詳見搜索引擎。
六、附錄
本文示例代碼已放到 Github。