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, NativeWebRequestGeneric access to request parameters, request & session attributes, without direct use of the Servlet API.
javax.servlet.ServletRequest, javax.servlet.ServletResponseChoose any specific request or response type — e.g. ServletRequest, HttpServletRequest, or Spring’s MultipartRequest, MultipartHttpServletRequest.
javax.servlet.http.HttpSessionEnforces 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.PrincipalCurrently authenticated user; possibly a specific Principal implementation class if known.
HttpMethodThe HTTP method of the request.
java.util.LocaleThe current request locale, determined by the most specific LocaleResolveravailable, in effect, the configured LocaleResolver/LocaleContextResolver.
java.util.TimeZone + java.time.ZoneIdThe time zone associated with the current request, as determined by a LocaleContextResolver.
java.io.OutputStream, java.io.WriterFor access to the raw response body as exposed by the Servlet API.
java.util.Map, org.springframework.ui.Model, org.springframework.ui.ModelMapFor access to the model for an error response, always empty.
RedirectAttributesSpecify 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.
@SessionAttributeFor 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.
@RequestAttributeFor 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 HttpMessageConverters and written to the response. See ResponseEntity.
StringA view name to be resolved with ViewResolver's and used together with the implicit model — determined through command objects and @ModelAttributemethods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).
ViewA 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.ModelAttributes to be added to the implicit model with the view name implicitly determined through a RequestToViewNameTranslator.
@ModelAttributeAn 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 objectThe view and model attributes to use, and optionally a response status.
voidA 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 OutputStreamargument, 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 valueIf 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

转载于:https://www.cnblogs.com/virde/p/springboot_exception.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot提供了一套默认的异常处理机制。一旦程序出现异常SpringBoot会向/error的URL发送请求,并通过BasicErrorController来处理该请求。默认情况下,SpringBoot会跳转到默认显示异常信息的页面来展示异常信息。如果我们希望将所有的异常统一跳转到自定义的错误页面,可以在src/main/resources/templates目录下创建一个名为error.html的页面。通过覆盖默认的错误页面,我们可以实现自定义的异常处理。 除了使用SpringBoot的默认配置外,还可以通过自定义错误页面来处理异常。我们可以在src/main/resources/templates目录下创建error.html页面,并将其命名为error。通过这种方式,我们可以自定义错误页面的内容和样式来展示异常信息。 在处理异常的过程中,可以关注ErrorMvcAutoConfiguration中的三个关键点。通过对SpringBoot错误处理机制源码的跟踪,我们可以更深入地了解异常处理的实现细节。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot异常处理](https://blog.csdn.net/Linging_24/article/details/126077782)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringBoot 异常处理详解](https://blog.csdn.net/qq_42402854/article/details/91415966)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值