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’s MultipartRequest , MultipartHttpServletRequest . |
javax.servlet.http.HttpSession |
Enforces the presence of a session. As a consequence, such an argument is never null . 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 specific Principal implementation class if known. |
HttpMethod |
The HTTP method of the request. |
java.util.Locale |
The current request locale, determined by the most specific LocaleResolver available, in effect, the configured LocaleResolver /LocaleContextResolver . |
java.util.TimeZone + java.time.ZoneId
|
The time zone associated with the current request, as determined by a LocaleContextResolver . |
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. See Redirect attributes and Flash 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 through HttpMessageConverter s and written to the response. See ResponseEntity. |
String |
A view name to be resolved with ViewResolver ‘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 a Model argument (see above). |
View |
A View 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 a Model 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 a RequestToViewNameTranslator . |
@ModelAttribute |
An attribute to be added to the model with the view name implicitly determined through a RequestToViewNameTranslator .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 a void return type (or null return value) is considered to have fully handled the response if it also has a ServletResponse , or an OutputStream argument, or an @ResponseStatus annotation. The same is true also if the controller has made a positive ETag or lastModified timestamp check (see Controllers for details).If none of the above is true, a void 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 by BeanUtils#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