Insight spring-boot web错误页跳转原理

引子

​ 为什么404的错误页显示 Whitelabel-page ?
​ 根据浏览器的网络请求分析,肯定是服务内部跳转处理的。
​ 根据返回Whitelabel 错误页的信息,肯定是spring-boot 处理的错误页
内部实现是如何跳转的?spring-boot 如何替web容器托管了错误页处理功能?

SpringBoot默认提供/Error映射,它以合理的方式处理所有错误,并在servlet容器中注册为“全局”错误页。对于Ajax请求,它将生成一个JSON响应,其中包含错误、HTTP状态和异常消息的详细信息。对于浏览器客户端,有一个“Whitelabel”错误页,它以HTML格式呈现相同的数据。

核心类

  • ErrorPageFilter 滤请求并转发请求到 error

  • BasicErrorController 默认error请求处理

  • ErrorMvcAutoConfiguration 默认错误注册配置、错误页跳转配置,例如:注册默认ErrorPage,注册 BasicErrorController

  • ResourceHttpRequestHandler 默认的404错误,就是统一由该Handler 产生

  • WhitelabelErrorViewConfiguration 我们看到的 spring-boot 默认错误页

实现原理分析

ErrorPageFilter 实现web错误页跳转是通过来,非嵌入式应用程序(即已部署的WAR文件)提供。作用是过滤请求并转发到错误页,而不是让容器(例如:Tomcat)处理它们。

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    // 包装response,支持错误分支判断,包装设计模式 
	ErrorWrapperResponse wrapped = new ErrorWrapperResponse(response);
	try {
         // 正常业务执行
		chain.doFilter(request, wrapped);
         // 如果请求response error(例如:404, 500),该Filter 进行判断转发到错误页
		if (wrapped.hasErrorToSend()) {
            // 服务内部定向跳转,这样,就请求到 BasicErrorController
            // request.getRequestDispatcher(errorPath).forward(request, response);
			handleErrorStatus(request, response, wrapped.getStatus(), wrapped.getMessage());
			response.flushBuffer();
		}
		// ...
	} catch (Throwable ex) {
		// ...
	}
}

ResourceHttpRequestHandler 优先判断404问题

public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	// For very general mappings (e.g. "/") we need to check 404 first
	Resource resource = getResource(request);
	if (resource == null) {
		logger.trace("No matching resource found - returning 404");
         // response.hasErrorToSend = true;
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
		return;
	}
    // ...
}

替换默认错误页

在默认路径下,创建自定义的错误页文件即可

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- templates/
             +- error/
             |   +- 5xx.ftl
             +- <other templates>

参考

https://docs.spring.io/spring-boot/docs/1.5.15.RELEASE/reference/htmlsingle/#boot-features-error-handling

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值