Springboot错误处理原理:
ErrorMvcAutoConfiguration
系统出现错误(4xx,5xx),ErrorPageCustomizer生效,定制错误信息,响应规则,来到/error请求,BasicErrorController会处理请求,根据其是html,还是其他客户端进行方法调用
1.DefaultErrorAttrubutes:
timestamp 时间戳
status 状态码
error 错误提示
exception 异常对象
message 异常消息
errors jsr303错误信息
2.BasicErrorController
默认的处理/error 请求
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties;
//处理html,浏览器发送的请求
@RequestMapping(
produces = {"text/html"}
)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
//获取要前往的错误页面
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}
//处理其他客户端
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = this.getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity(status);
} else {
Map<String, Object> body = this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL));
return new ResponseEntity(body, status);
}
}
}
3. ErrorPageCustomizer
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(new ErrorPage[]{errorPage});
}
@Value("${error.path:/error}")
private String path = "/error";
4.DefaultErrorViewResolverConfiguration
private ModelAndView resolve(String viewName, Map<String, Object> model) {
//获取一个页面 error/4xx
String errorViewName = "error/" + viewName;
//模板引擎可以解析这个页面,使用模板引擎
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
//模板引擎不可以用,在静态资源文件夹里面寻找
return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
}
private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
String[] var3 = this.resources.getStaticLocations();
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
String location = var3[var5];
try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
if (resource.exists()) {
return new ModelAndView(new DefaultErrorViewResolver.HtmlResourceView(resource), model);
}
} catch (Exception var8) {
}
}
return null;
}
定制错误页面
templeates包下新建error包,里面存放4xx,5xx.html
或者在静态资源文件夹里面存放