1.在Spring boot 中如果发生错误,浏览器访问会默认跳转到Whitelabel Error Page 这个错误页面,如果是客户端访问的话返回JSON格式的错误数据,说明spring boot 为全局的异常处理做了自适应处理,浏览器和客户端分别响应不同的形式的错误数据。
{
"timestamp": 1534818780468,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/amain.html"
}
2.spring boot 对错误信息的处理都在它的自动的配置里实现,对于异常的自动配置都在org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration 中实现。首先,我们来看浏览器端如何响应错误。这个自动配置类为容器中添加一下几个组件:
(1)当系统发生错误以后,ErrorPageCustomizer 会响应错误,就会发送/error请求去处理错误。
@Bean public ErrorPageCustomizer errorPageCustomizer() { return new ErrorPageCustomizer(this.serverProperties); }
(2)由BasicErrorController 去处理error请求,在BasicErrorController 中根据请求报文头的produces = "text/html" 判断是浏览器还是客户端请求, 用方法errorHtml 响应浏览器请求的错误页面, error响应客户端请求而的错误页面 。
@Bean @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers); }
(3)接下来由 DefaultErrorViewResolver 去解析错误页面的视图,最终解析出来的视图的名称是: error/ +status,如果模板引擎可用的话就在模板文件夹下的error文件夹下找以错误状态码命名的错误页面,如果不可用则在静态资源文件夹下的error文件夹下找以错误状态码命名的错误文件。如果没有错误状态码命名的出错误文件,还可以按照以4开头的错误去找4xx命名的错误页面,5开头的错误去找5xx命名的错误页面,如果以上都没有的话就会来到默认的Whitelabel Error Page 这个错误页面
@Bean @ConditionalOnBean(DispatcherServlet.class) @ConditionalOnMissingBean public DefaultErrorViewResolver conventionErrorViewResolver() { return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties); }
(4)DefaultErrorAttributes这个组件里面放置了错误信息,封装了
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误
这些错误信息
@Bean @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes() { return new DefaultErrorAttributes(); }
(5)综上所述,对于浏览器端的错误响应页面,我们只需要在模板文件夹夹下简历error文件夹,在这里放置以错误状态码命名的错误页面,或者放置以4xx,5xx命名的错误页面,来响应所有以4或者5开头的错误页面。