实战代码跳转至:https://blog.csdn.net/weixin_43393069/article/details/110727506
1. spring boot错误处理原理–源码分析
spring boot 错误自动配置源码位置:
源码中的几个核心组件:
DefaultErrorAttributes
BasicErrorController
ErrorPageCustomizer
DefaultErrorViewResolver
spring boot默认处理错误的步骤:
系统发生4xx或5xx错误时,ErrorPageCustomizer
就会生效(定制错误的响应规则,获取配置文件中的error.path的值,如果没有配置,默认使用/error路径)即,系统出现错误后来到/error请求进行处理。
/error请求则是由BasicErrorController
处理,
BasicErrorController
分别实现了html和JSON格式的返回数据,通过不同客户端发送请求头之间的区别实现自适应
浏览器发送的请求头:
其他客户端发送的请求头
响应页面的处理:
具体去到那个页面则由DefaultErrorViewResolver
解析得到
public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {
private static final Map<Series, String> SERIES_VIEWS;
static {
Map<Series, String> views = new EnumMap<>(Series.class);
//4开头的页面都可匹配,如有精确匹配则匹配精确页面
views.put(Series.CLIENT_ERROR, "4xx");
//5开头的页面都可匹配,如有精确匹配则匹配精确页面
views.put(Series.SERVER_ERROR, "5xx");
SERIES_VIEWS = Collections.unmodifiableMap(views);
}
...
@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;
}
//springboot默认去找 "error/" + viewName页面,如 "error/404"
private ModelAndView resolve(String viewName, Map<String, Object> model) {
String errorViewName = "error/" + viewName;
//如果模板引擎可以解析这个地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
this.applicationContext);
if (provider != null) {
//模板引擎可用的情况下返回到此视图,地址为errorViewName,内容为model
return new ModelAndView(errorViewName, model);
}
//模板引擎不可用时则调用resolveResource
return resolveResource(errorViewName, model);
}
private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
//从静态资源文件夹下找viewName对应的页面,如 "error/404"
for (String location : this.resourceProperties.getStaticLocations()) {
try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
if (resource.exists()) {
return new ModelAndView(new HtmlResourceView(resource), model);
}
}
catch (Exception ex) {
}
}
return null;
}
定制错误页面
1,如果存在模板引擎,将错误页面命名为错误状态码。html
放在模板引擎文件夹里面的error文件夹下即可.
页面可以获取到的信息:timestamp status error exception message errors
2. 如果不存在模板引擎或找不到,则去静态资源文件夹下找,但是无法动态获取数据
3. 如果都找不到对应的页面,则使用spring boot默认的空白页