W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
處理請求的過程中,Spring MVC可能會拋出一些的異常。SimpleMappingExceptionResolver
可以根據(jù)需要很方便地將任何異常映射到一個默認的錯誤視圖。但,如果客戶端是通過自動檢測響應(yīng)的方式來分發(fā)處理異常的,那么后端就需要為響應(yīng)設(shè)置對應(yīng)的狀態(tài)碼。根據(jù)拋出異常的類型不同,可能需要設(shè)置不同的狀態(tài)碼來標識是客戶端錯誤(4xx)還是服務(wù)器端錯誤(5xx)。
默認處理器異常解析器DefaultHandlerExceptionResolver
會將Spring MVC拋出的異常轉(zhuǎn)換成對應(yīng)的錯誤狀態(tài)碼。該解析器在MVC命名空間配置或MVC Java配置的方式下默認已經(jīng)被注冊了,另外,通過DispatcherServlet
注冊也是可行的(即不使用MVC命名空間或Java編程方式進行配置的時候)。下表列出了該解析器能處理的一些異常,及他們對應(yīng)的狀態(tài)碼。
異常 | HTTP狀態(tài)碼 |
---|---|
BindException | 400 (無效請求) |
ConversionNotSupportedException | 500 (服務(wù)器內(nèi)部錯誤) |
HttpMediaTypeNotAcceptableException | 406 (不接受) |
HttpMediaTypeNotSupportedException | 415 (不支持的媒體類型) |
HttpMessageNotReadableException | 400 (無效請求) |
HttpMessageNotWritableException | 500 (服務(wù)器內(nèi)部錯誤) |
HttpRequestMethodNotSupportedException | 405 (不支持的方法) |
MethodArgumentNotValidException | 400 (無效請求) |
MissingServletRequestParameterException | 400 (無效請求) |
MissingServletRequestPartException | 400 (無效請求) |
NoHandlerFoundException | 404 (請求未找到) |
NoSuchRequestHandlingMethodException | 404 (請求未找到) |
TypeMismatchException | 400 (無效請求) |
MissingPathVariableException | 500 (服務(wù)器內(nèi)部錯誤) |
NoHandlerFoundException | 404 (請求未找到) |
以下待翻譯。
The DefaultHandlerExceptionResolver
works transparently by setting the status of the response. However, it stops short of writing any error content to the body of the response while your application may need to add developer- friendly content to every error response for example when providing a REST API. You can prepare a ModelAndView
and render error content through view resolution?--?i.e. by configuring a ContentNegotiatingViewResolver
, MappingJackson2JsonView
, and so on. However, you may prefer to use@ExceptionHandler
methods instead.
If you prefer to write error content via @ExceptionHandler
methods you can extend ResponseEntityExceptionHandler
instead. This is a convenient base for @ControllerAdvice
classes providing an @ExceptionHandler
method to handle standard Spring MVC exceptions and return ResponseEntity
. That allows you to customize the response and write error content with message converters. See the ResponseEntityExceptionHandler
javadocs for more details.
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: