【springboot异常处理】

1,Java Servlet规范

异常处理

在web.xml中定义Exception和error-code的映射。

<!-- 根据状态码配置 -->
<error-page> 
    <error-code>404</error-code>          
    <location>/404.html</location>
</error-page>

<!-- 状态码为0时可以匹配所有的状态码 -->
<error-page> 
    <error-code>0</error-code>          
    <location>/error.html</location>
</error-page>

<!-- 根据异常类型配置 -->
<error-page> 
    <exception-type>java.lang.NullPointerException</exception-type>          
    <location>/error.html</location>
</error-page>
触发异常

HttpServletResponse.setError();
HttpServletResponse.sendError(status,msg);

2,tomcat 异常处理实现

tomcat请求处理流程
  1. 线程模型
    在这里插入图片描述

  2. 请求处理流程
    在这里插入图片描述

异常发生时核心处理类

当异常发生时,首先在StandardHostValve 中匹配,匹配的规则是

  1. 先根据Exception去找错误页面
  2. 再根据code去找错误页面

找到对应的页面后,dispatch到相应的页面,返回给前端进行展示。
如果没有匹配到相应的页面,tomcat使用以下两种Value进行异常处理。

ErrorReportValve
用于在界面上展示错误信息,也就是常见的错误提示:
在这里插入图片描述

StandardWrapperValve
收集执行Servlet过程中的错误信息,给ErrorReportValve进行展示。

3,springmvc 异常定制以及扩展

请求处理流程

在这里插入图片描述

使用@ControllerAdvice & @ExceptionHandler 配置全局异常处理器

用于处理 HandlerMethod(上图中 Handler) 执行过程中抛出的异常

未配置全局异常处理或者没有匹配到异常时的处理流程
  1. springboot在启动时,自动配置机制,使用 ErrorMvcAutoConfiguration 中注册:BasicErrorController
  2. 同时,注册code为0的ErrorPage
    org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration.ErrorPageCustomizer#registerErrorPages
		@Override
		public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
			ErrorPage errorPage = new ErrorPage(
					this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
			errorPageRegistry.addErrorPages(errorPage);
		}

by the way:code为0的错误页面映射,tomcat中的处理逻辑如下:

//org.apache.catalina.valves.ErrorReportValve

    protected void report(Request request, Response response, Throwable throwable) {

        int statusCode = response.getStatus();

        // Do nothing on a 1xx, 2xx and 3xx status
        // Do nothing if anything has been written already
        // Do nothing if the response hasn't been explicitly marked as in error
        //    and that error has not been reported.
        if (statusCode < 400 || response.getContentWritten() > 0 || !response.setErrorReported()) {
            return;
        }

        // If an error has occurred that prevents further I/O, don't waste time
        // producing an error report that will never be read
        AtomicBoolean result = new AtomicBoolean(false);
        response.getCoyoteResponse().action(ActionCode.IS_IO_ALLOWED, result);
        if (!result.get()) {
            return;
        }

        ErrorPage errorPage = null;
        if (throwable != null) {
            errorPage = errorPageSupport.find(throwable);
        }
        if (errorPage == null) {
            errorPage = errorPageSupport.find(statusCode);
        }
        if (errorPage == null) {
            // Default error page
            errorPage = errorPageSupport.find(0);
        }
	... //忽略部分代码
	}

  1. 经过code为0的映射处理后,tomcat container组件会把请求dispatch到“/error”页面,最终找到BasicErrorController 处理器:
    BasicErrorController 处理器的处理逻辑如下:
    BasicErrorController 通过 Accept 头判断需要生成哪种 MediaType 的响应
    3.1 如果要的不是 text/html,走 MessageConverter 流程
    3.2 如果需要 text/html,走 mvc 流程,此时又分两种情况
    a. 配置了 ErrorViewResolver,根据状态码去找 View
    b. 没配置或没找到,用 BeanNameViewResolver 根据一个固定为 error 的名字找到 View,即所谓的 WhitelabelErrorView
以上处理过程中的未捕获异常,交给tomcat去处理异常

返回给tomcat的ErrorReportValve去处理,展示异常如前图所示。

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、付费专栏及课程。

余额充值