从01开始 从01开始
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)

peterjxl

人生如逆旅,我亦是行人
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)
  • JavaSE

  • JavaSenior

  • JavaEE

  • JavaWeb

  • Spring

  • 主流框架

  • SpringMVC

  • SpringBoot

    • SpringBoot教程-尚硅谷

      • SpringBoot课程介绍
      • Spring和SpringBoot
      • HelloWorld
      • 了解自动配置原理
      • 底层注解-@Configuration详解
      • 底层注解-@Import导入组件
      • 底层注解-@Conditional条件装配
      • 原生配置文件引入-@ImportResource
      • 底层注解-配置绑定@ConfigurationProperties
      • 自动配置原理
      • 自动配置流程
      • Lombok简化开发
      • DevTools
      • Spring-Initailizr
      • 配置文件-Yaml用法
      • Web开发简介
      • web开发-静态资源规则于定制化
      • 静态资源配置原理
      • Rest映射及源码解析
      • 请求映射原理
      • 常用参数注解使用
      • MatrixVariable:矩阵变量
      • 各种类型参数解析原理
      • Servlet-API参数解析原理
      • Model、Map参数解析原理
      • 自定义对象参数绑定原理
      • 自定义Converter原理
      • 数据响应原理
      • 内容协商原理
      • 基于请求参数的内容原理
      • 自定义MessageConverter原理
      • Thymeleaf初体验
      • web实验-后台管理系统
      • web实验-抽取公共页面
      • web实验-遍历数据
      • 源码分析-视图解析器与视图
      • 拦截器-登录检查与静态资源放行
      • 拦截器的执行时机和原理
      • 单文件和多文件上传的使用
      • 文件上传原理
      • 错误处理机制
      • 错误处理-底层组件源码分析
        • 异常处理-自动配置原理
        • BasicErrorController​
        • Error-View
        • ​DefaultErrorViewResolver​
        • DefaultErrorAttributes​
        • 最后
      • 异常处理流程
      • 几种异常处理原理
      • Web原生对象注入
      • 嵌入式Servlet容器
      • 定制化原理
      • 数据库场景的自动配置分析和整合测试
      • 自定义方式整合Druid
      • 通过starter整合Druid
      • 整合Mybatis
      • 使用注解整合Mybatis
      • 整合MybatisPlus操作数据库
      • MybatisPlus-列表分页展示
      • 整合Redis
      • 单元测试-Junit5
      • 单元测试-断言机制
      • 单元测试-前置条件
      • 单元测试-嵌套测试
      • 单元测试-参数化测试
      • 指标监控-基本概念
      • 指标监控-配置EndPoint
      • 指标监控-可视化
      • 原理解析-Profile功能
      • 配置文件深入
      • 自定义Starter
      • SpringApplication初始化过程
      • SpringBoot完整启动过程
      • SpringBoot
  • Java并发

  • Java源码

  • JVM

  • 韩顺平

  • Java
  • Java
  • SpringBoot
  • SpringBoot教程-尚硅谷
2023-08-22
目录

错误处理-底层组件源码分析

# 420.错误处理-底层组件源码分析

本文讲讲原理,掌握原理后,就能更方便地定制化。   ‍

# 异常处理-自动配置原理

之前我们讲了SpringBoot的默认处理,那么这些处理肯定也是配置在源码的;

我们可以在IDEA中打开spring-boot-autoconfigure-2.3.4.RELEASE.jar,

然后打开该目录:org\springframework\boot\autoconfigure\web\servlet\error:

​​

‍

其中ErrorMvcAutoConfiguration​​,就是自动配置异常处理规则的;

‍

‍

‍

‍

‍

‍

# BasicErrorController​

在ErrorMvcAutoConfiguration​类中,还配置了一个ErrorController​:

@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes,
		ObjectProvider<ErrorViewResolver> errorViewResolvers) {
	return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
			errorViewResolvers.orderedStream().collect(Collectors.toList()));
}
1
2
3
4
5
6
7

‍

‍

该类的源码如下:

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
1
2
3

‍

可以看到,首先是一个Controller,然后定义了访问路径:先取出我们定义的配置文件中的server.error.path​,如果没有,则取出error.path​;还是没有,则会取值/error​,也就是我们之前说的默认值。

‍

既然是Controller,那么就会响应内容,例如下面第一个方法是响应HTML,第二个方法是响应JSON:

@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
	HttpStatus status = getStatus(request);
	Map<String, Object> model = Collections
			.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
	response.setStatus(status.value());
	ModelAndView modelAndView = resolveErrorView(request, response, status, model);
	return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}





@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
	HttpStatus status = getStatus(request);
	if (status == HttpStatus.NO_CONTENT) {
		return new ResponseEntity<>(status);
	}
	Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
	return new ResponseEntity<>(body, status);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

‍

‍

如果是响应HTML,则是响应error(第8行):

return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
1

‍

如果是响应JSON,则直接封装JSON:

Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
1
2

‍

‍

# Error-View

​ErrorMvcAutoConfiguration​就定义了一个叫做error的组件,其是一个View类型:

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
@Conditional(ErrorTemplateMissingCondition.class)
protected static class WhitelabelErrorViewConfiguration {

	private final StaticView defaultErrorView = new StaticView();

	@Bean(name = "error")
	@ConditionalOnMissingBean(name = "error")
	public View defaultErrorView() {
		return this.defaultErrorView;
	}

	// If the user adds @EnableWebMvc then the bean name view resolver from
	// WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.
	@Bean
	@ConditionalOnMissingBean
	public BeanNameViewResolver beanNameViewResolver() {
		BeanNameViewResolver resolver = new BeanNameViewResolver();
		resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
		return resolver;
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

‍

可以看到还定义了BeanNameViewResolver​组件,这个就是通过Bean的名字,来寻找视图的一种视图解析器。

而StaticView​,里面的render方法是这样的:

@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    //......
    builder.append("<html><body><h1>Whitelabel Error Page</h1>")
    .append("<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>") .append("<div id='created'>")
    .append(timestamp).append("</div>")
    .append("<div>There was an unexpected error (type=").append(htmlEscape(model.get("error")))
    .append(", status=").append(htmlEscape(model.get("status"))).append(").</div>");
    //.....
1
2
3
4
5
6
7
8
9

所以这就是我们之前看到的默认错误页面。

‍

# ​DefaultErrorViewResolver​

还配置了一个id叫做conventionErrorViewResolver​的组件,其类型是DefaultErrorViewResolver​:

@Configuration(proxyBeanMethods = false)
static class DefaultErrorViewResolverConfiguration {

    private final ApplicationContext applicationContext;

    private final ResourceProperties resourceProperties;

    DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext,
			ResourceProperties resourceProperties) {
	this.applicationContext = applicationContext;
	this.resourceProperties = resourceProperties;
    }

    @Bean
    @ConditionalOnBean(DispatcherServlet.class)
    @ConditionalOnMissingBean(ErrorViewResolver.class)
    DefaultErrorViewResolver conventionErrorViewResolver() {
	   return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties);
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

‍

该类部分源码如下:

public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {

	private static final Map<Series, String> SERIES_VIEWS;

	static {
		Map<Series, String> views = new EnumMap<>(Series.class);
		views.put(Series.CLIENT_ERROR, "4xx");
		views.put(Series.SERVER_ERROR, "5xx");
		SERIES_VIEWS = Collections.unmodifiableMap(views);
	}
1
2
3
4
5
6
7
8
9
10

可以看到,定义了客户端错误就是4xx,服务端错误是5xx

‍

既然是视图解析器,那么就会解析请求返回内容,例如resolveErrorView方法,就回调用resolve方法,得到modelAndView对象并返回:

@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
	ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
	if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
		modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
	}
	return modelAndView;
}
1
2
3
4
5
6
7
8

会传参status,也就是HTTP状态码;

‍

‍

然后resolve方法,就会拼接错误路径 + HTTP状态码,来拼接视图的名字:

private ModelAndView resolve(String viewName, Map<String, Object> model) {
	String errorViewName = "error/" + viewName;
	TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
			this.applicationContext);
	if (provider != null) {
		return new ModelAndView(errorViewName, model);
	}
	return resolveResource(errorViewName, model);
}
1
2
3
4
5
6
7
8
9

‍

所以,如果发生了404错误,那么resolve方法收到的参数viewName就是404,然后会拼接成 /error/404.html页面;

‍

# DefaultErrorAttributes​

SpringBoot还自动配置了DefaultErrorAttributes​这个组件;

@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
	return new DefaultErrorAttributes();
}
1
2
3
4
5

‍

​DefaultErrorAttributes​类,主要就是定义了错误信息应该包含什么,例如message,trace等属性,例如这是其getErrorAttributes​方法:

@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
	Map<String, Object> errorAttributes = getErrorAttributes(webRequest, options.isIncluded(Include.STACK_TRACE));
	if (Boolean.TRUE.equals(this.includeException)) {
		options = options.including(Include.EXCEPTION);
	}
	if (!options.isIncluded(Include.EXCEPTION)) {
		errorAttributes.remove("exception");
	}
	if (!options.isIncluded(Include.STACK_TRACE)) {
		errorAttributes.remove("trace");
	}
	if (!options.isIncluded(Include.MESSAGE) && errorAttributes.get("message") != null) {
		errorAttributes.put("message", "");
	}
	if (!options.isIncluded(Include.BINDING_ERRORS)) {
		errorAttributes.remove("errors");
	}
	return errorAttributes;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

默认会包含很多属性,if​判断里主要是看是否要包含,来决定是否移除。

‍

‍

‍

该类实现了ErrorAttributes​和HandlerExceptionResolver​接口:

public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered {
1

这两个接口是什么,我们后续再说

‍

‍

# 最后

‍

我们说了很多自动配置的东西

  • 想要修改返回的错误信息,就修改DefaultErrorAttributes​
  • 想要修改默认的错误路径(/error),就修改BasicErrorController​
  • 想要修改默认的错误页面路径,就修改​DefaultErrorViewResolver​

‍

至于他们是怎么串起来的,下节课再说

‍

在GitHub上编辑此页 (opens new window)
上次更新: 2023/8/23 10:10:57
错误处理机制
异常处理流程

← 错误处理机制 异常处理流程→

Theme by Vdoing | Copyright © 2022-2023 粤ICP备2022067627号-1 粤公网安备 44011302003646号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式