前言
關于之前的一篇所講到的表單驗證中提到,如果產生錯誤,可以得到錯誤的信息,但是返回值的問題卻沒有考慮。
其中所提到的Controller:
1
2
3
4
5
6
7
8
9
10
11
12
|
@RequestMapping (value = "/doRegister" , method = RequestMethod.POST) public @ResponseBody User doRegister( @Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { List<ObjectError> list = result.getAllErrors(); for (ObjectError error : list) { System.out.println(error.getDefaultMessage()); } return null ; } System.out.println( "注冊.." ); return user; } |
如果驗證不通過,我們不應該返回null的,這會對前端來說并不友好。
所以我們應該定義一個統一的返回格式:
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
|
public class ReturnType { private int code; private User data; private String msg; public ReturnType( int code, String msg, User data) { this .code = code; this .msg = msg; this .data = data; } public int getCode() { return code; } public void setCode( int code) { this .code = code; } public User getData() { return data; } public void setData(User data) { this .data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this .msg = msg; } } |
這樣一來,返回的結果中的json的格式是固定的。
雖然我們的希望是好的,但是并不是總是可以這樣的,因為不管是對底層的數據庫操作過程,還是業務層的處理過程,還是控制層的處理過程,都不可避免會遇到各種可預知的、不可預知的異常需要處理。
如果存在下面這種情況:
1
2
3
4
|
@RequestMapping (value = "/doRegister" , method = RequestMethod.POST) public @ResponseBody ReturnType doRegister( @Valid User user, BindingResult result, Model model) throws Exception { throw new Exception( "new Exception" ); } |
這就好像在調用Service層代碼的時候,執行方法的過程中遇到了一個異常,那么回得到什么樣的結果呢?
無論如何,返回的肯定不是我們之前定義好的格式的返回值。
那我們應該怎么做呢?
這里就需要進行統一的異常處理了。
1
2
3
4
5
6
7
8
9
10
11
12
|
@ControllerAdvice public class ExceptionHandle { /* 表明這個handler只處理什么類型的異常 * */ @ExceptionHandler (value = Exception. class ) // 返回值為json或者其他對象 @ResponseBody public ReturnType handle(Exception e) { return new ReturnType(- 1 , e.getMessage(), null ); } } |
創建這么一個handler類,當Controller拋出異常的時候,就會委托給這個類其中的方法進行執行。
這樣一來,就不會出現即使拋出異常,也不會得到不是我們期望的返回值的結果了。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://blog.csdn.net/a60782885/article/details/68491592