W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
處理請(qǐng)求的過程中,Spring MVC可能會(huì)拋出一些的異常。SimpleMappingExceptionResolver
可以根據(jù)需要很方便地將任何異常映射到一個(gè)默認(rèn)的錯(cuò)誤視圖。但,如果客戶端是通過自動(dòng)檢測(cè)響應(yīng)的方式來分發(fā)處理異常的,那么后端就需要為響應(yīng)設(shè)置對(duì)應(yīng)的狀態(tài)碼。根據(jù)拋出異常的類型不同,可能需要設(shè)置不同的狀態(tài)碼來標(biāo)識(shí)是客戶端錯(cuò)誤(4xx)還是服務(wù)器端錯(cuò)誤(5xx)。
默認(rèn)處理器異常解析器DefaultHandlerExceptionResolver
會(huì)將Spring MVC拋出的異常轉(zhuǎn)換成對(duì)應(yīng)的錯(cuò)誤狀態(tài)碼。該解析器在MVC命名空間配置或MVC Java配置的方式下默認(rèn)已經(jīng)被注冊(cè)了,另外,通過DispatcherServlet
注冊(cè)也是可行的(即不使用MVC命名空間或Java編程方式進(jìn)行配置的時(shí)候)。下表列出了該解析器能處理的一些異常,及他們對(duì)應(yīng)的狀態(tài)碼。
異常 | HTTP狀態(tài)碼 |
---|---|
BindException | 400 (無效請(qǐng)求) |
ConversionNotSupportedException | 500 (服務(wù)器內(nèi)部錯(cuò)誤) |
HttpMediaTypeNotAcceptableException | 406 (不接受) |
HttpMediaTypeNotSupportedException | 415 (不支持的媒體類型) |
HttpMessageNotReadableException | 400 (無效請(qǐng)求) |
HttpMessageNotWritableException | 500 (服務(wù)器內(nèi)部錯(cuò)誤) |
HttpRequestMethodNotSupportedException | 405 (不支持的方法) |
MethodArgumentNotValidException | 400 (無效請(qǐng)求) |
MissingServletRequestParameterException | 400 (無效請(qǐng)求) |
MissingServletRequestPartException | 400 (無效請(qǐng)求) |
NoHandlerFoundException | 404 (請(qǐng)求未找到) |
NoSuchRequestHandlingMethodException | 404 (請(qǐng)求未找到) |
TypeMismatchException | 400 (無效請(qǐng)求) |
MissingPathVariableException | 500 (服務(wù)器內(nèi)部錯(cuò)誤) |
NoHandlerFoundException | 404 (請(qǐng)求未找到) |
以下待翻譯。
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號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: