Spring MVC 處理一般的異常

2018-07-26 14:34 更新

處理請(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)碼
BindException400 (無效請(qǐng)求)
ConversionNotSupportedException500 (服務(wù)器內(nèi)部錯(cuò)誤)
HttpMediaTypeNotAcceptableException406 (不接受)
HttpMediaTypeNotSupportedException415 (不支持的媒體類型)
HttpMessageNotReadableException400 (無效請(qǐng)求)
HttpMessageNotWritableException500 (服務(wù)器內(nèi)部錯(cuò)誤)
HttpRequestMethodNotSupportedException405 (不支持的方法)
MethodArgumentNotValidException400 (無效請(qǐng)求)
MissingServletRequestParameterException400 (無效請(qǐng)求)
MissingServletRequestPartException400 (無效請(qǐng)求)
NoHandlerFoundException404 (請(qǐng)求未找到)
NoSuchRequestHandlingMethodException404 (請(qǐng)求未找到)
TypeMismatchException400 (無效請(qǐng)求)
MissingPathVariableException500 (服務(wù)器內(nèi)部錯(cuò)誤)
NoHandlerFoundException404 (請(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 ContentNegotiatingViewResolverMappingJackson2JsonView, 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.


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)