springboot错误处理机制
浏览器页面返回的页面是一个有错误信息的页面;其他的客户端返回的是json 数据
可以参照ErrorMvcAutoConfiguraation 配置类
原理:ErrorMvcAutoConfiguraation
添加了以下组件:
- DefaultErrorAttributes
- BasicErrorController
- ErrorPageCustomizer
- DefaultErrorViewResolver
详细分析
一旦页面出现4xx或者5xx 的错误;ErrorPageCustomizer 生效,定制错误响应规则(定制错误请求的url);请求/error 会来到BasicErroeController,处理请求
1. ErrorPageCustomizer
注册错误页面:
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(new ErrorPage[]{errorPage});
}
getPath() 获取页面的请求错误页面的请求路径
@Value("${error.path:/error}")
private String path = "/error";
public String getPath() {
return this.path;
}
产生一个错误请求的url
2. BasicErrorController
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers);
}
表明: 处理/error 请求
@Controller
@RequestMapping({"${server.error