Spring MVC 處理一般的異常

2018-07-26 14:34 更新

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

以下待翻譯。

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)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號