Springboot 異常處理
@ExceptionHandler 如何使用
可以用@ExceptionHandler 註解方法去處理異常情況,@ExceptionHandler註解可以在@Controller,@RestController,@ControllerAdvice,@RestControllerAdvice中使用
在@RestController,@RestControllerAdvice註解的類中使用時方法會預設加上@ResponseBody
FOR EXAMPLE:
@Controller public class SimpleController { @ExceptionHandler public ResponseEntity<String> handle(IOException ex) { // ... } } @ControllerAdvice(annotations = RestController.class) public class ExampleAdvice1 { @ExceptionHandler public ResponseEntity<String> handle(IOException ex) { // ... } }
上面的例子會預設捕獲Exception下所有的異常情況,如果需要更詳細的捕獲,可以用如下方式
FOR EXAMPLE:
@ExceptionHandler(BindException.class) public ResponseEntity<String> handle(BindException ex) { // ... } @ExceptionHandler({RemoteException.class,FileSystemException.class}) public ResponseEntity<String> handle(Exception ex) { // ... }
@ExceptionHandler 方法支援的引數列表
方法引數型別 | Description |
---|---|
Exception | 異常的詳細情況 |
HandlerMethod | 訪問異常發生的控制器方法的詳細情況 |
WebRequest
,NativeWebRequest
|
Generic access to request parameters, request & session attributes, without direct use of the Servlet API. |
javax.servlet.ServletRequest
,javax.servlet.ServletResponse
|
Choose any specific request or response type — e.g.ServletRequest
,HttpServletRequest
, or Spring’sMultipartRequest
,MultipartHttpServletRequest
. |
javax.servlet.http.HttpSession
|
Enforces the presence of a session. As a consequence, such an argument is nevernull
.Note:
Session access is not thread-safe. Consider setting theRequestMappingHandlerAdapter
's "synchronizeOnSession" flag to "true" if multiple requests are allowed to access a session concurrently. |
java.security.Principal
|
Currently authenticated user; possibly a specificPrincipal
implementation class if known. |
HttpMethod
|
The HTTP method of the request. |
java.util.Locale
|
The current request locale, determined by the most specificLocaleResolver
available, in effect, the configuredLocaleResolver
/LocaleContextResolver
. |
java.util.TimeZone
+java.time.ZoneId
|
The time zone associated with the current request, as determined by aLocaleContextResolver
. |
java.io.OutputStream
,java.io.Writer
|
For access to the raw response body as exposed by the Servlet API. |
java.util.Map
,org.springframework.ui.Model
,org.springframework.ui.ModelMap
|
For access to the model for an error response, always empty. |
RedirectAttributes
|
Specify attributes to use in case of a redirect — i.e. to be appended to the query string, and/or flash attributes to be stored temporarily until the request after redirect. SeeRedirect attributes andFlash attributes . |
@SessionAttribute
|
For access to any session attribute; in contrast to model attributes stored in the session as a result of a class-level@SessionAttributes
declaration. See@SessionAttribute
for more details. |
@RequestAttribute
|
For access to request attributes. See@RequestAttribute for more details. |
@ExceptionHandler 方法支援的返回型別說明
返回值型別 | 描述 |
---|---|
@ResponseBody
|
加上@ResponseBody註解可以返回JSON內容 |
HttpEntity<B>
,ResponseEntity<B>
|
The return value specifies the full response including HTTP headers and body be converted throughHttpMessageConverter
s and written to the response. SeeResponseEntity
. |
String
|
A view name to be resolved withViewResolver
's and used together with the implicit model — determined through command objects and@ModelAttribute
methods. The handler method may also programmatically enrich the model by declaring aModel
argument (see above). |
View
|
AView
instance to use for rendering together with the implicit model — determined through command objects and@ModelAttribute
methods. The handler method may also programmatically enrich the model by declaring aModel
argument (see above). |
java.util.Map
,org.springframework.ui.Model
|
Attributes to be added to the implicit model with the view name implicitly determined through aRequestToViewNameTranslator
. |
@ModelAttribute
|
An attribute to be added to the model with the view name implicitly determined through aRequestToViewNameTranslator
.Note that@ModelAttribute
is optional. See "Any other return value" further below in this table. |
ModelAndView
object |
The view and model attributes to use, and optionally a response status. |
void
|
A method with avoid
return type (ornull
return value) is considered to have fully handled the response if it also has aServletResponse
, or anOutputStream
argument, or an@ResponseStatus
annotation. The same is true also if the controller has made a positive ETag or lastModified timestamp check (seeControllers
for details).If none of the above is true, avoid
return type may also indicate "no response body" for REST controllers, or default view name selection for HTML controllers. |
Any other return value | If a return value is not matched to any of the above, by default it is treated as a model attribute to be added to the model, unless it is a simple type, as determined byBeanUtils#isSimpleProperty in which case it remains unresolved. |
參考連結
- 官網文件:https://docs.spring.io/spring/docs/5.0.12.RELEASE/spring-framework-reference/web.html#mvc-ann-exceptionhandler