接着上一篇《springmvc 經過異常加強返回給客戶端統一格式》講經過spring ControllerAdvice對各類異常進行攔截處理,統一格式返回給客戶端。html
接下來咱們更精細的講,經過@ExceptionHandler攔截異常,提示參數客戶端哪些參數沒有傳或參數數據類型不一致,方便客戶端服務端聯調測試。java
簡述一下上一篇攔截異常主要流程:web
1.自定義一個類RestExceptionHandler,並使用@ControllerAdvice註解,表示這個類是控制器加強;spring
2.在RestExceptionHandler新建一個方法,並使用@ExceptionHandler({Exception.clss})註解在方法上,表示這個方法處理異常信息。sql
3.在springMvc.xml裏配置express
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
@ExceptionHandler註解容許咱們指定異常類型進行攔截處理,也能夠對自定義異常攔截。mvc
那麼咱們來看看機springmvc對於http請求的異常類型。nosql
Exception Typepost |
HTTP Status Code 測試 |
ConversionNotSupportedException |
500 (Internal Server Error) |
HttpMediaTypeNotAcceptableException |
406 (Not Acceptable) |
HttpMediaTypeNotSupportedException |
415 (Unsupported Media Type) |
HttpMessageNotReadableException |
400 (Bad Request) |
HttpMessageNotWritableException |
500 (Internal Server Error) |
HttpRequestMethodNotSupportedException |
405 (Method Not Allowed) |
MissingServletRequestParameterException |
400 (Bad Request) |
NoSuchRequestHandlingMethodException |
404 (Not Found) |
TypeMismatchException |
400 (Bad Request) |
springmvc內部已經爲咱們定義好了http請求常見的異常類型,咱們只須要使用@ExceptionHandler({MissingServletRequestParameterException.class})註解在方法上,方法參數類型就是咱們指定的異常類型,就能獲取到缺乏參數異常時的異常對象。
//參數類型不匹配 //getPropertyName()獲取數據類型不匹配參數名稱 //getRequiredType()實際要求客戶端傳遞的數據類型 @ExceptionHandler({TypeMismatchException.class}) @ResponseBody public String requestTypeMismatch(TypeMismatchException ex){ ex.printStackTrace(); return outputJson(-400, "參數類型不匹配,參數" + ex.getPropertyName() + "類型應該爲" + ex.getRequiredType()); } //缺乏參數異常 //getParameterName() 缺乏的參數名稱 @ExceptionHandler({MissingServletRequestParameterException.class}) @ResponseBody public String requestMissingServletRequest(MissingServletRequestParameterException ex){ ex.printStackTrace(); return outputJson(-400, "缺乏必要參數,參數名稱爲" + ex.getParameterName()); }
這樣無論是參數異常,仍是數據類型異常,仍是請求方法異常,都能作到精細的處理,精確到某個方法的參數和數據類型,給客戶端提示更有意義的信息。