Spring Boot异常处理详解
在Spring MVC异常处理详解中,介绍了Spring MVC的异常处理体系,本文将讲解在此基础上Spring Boot为我们做了哪些工作。下图列出了Spring Boot中跟MVC异常处理相关的类。
Spring Boot在启动过程中会根据当前环境进行AutoConfiguration,其中跟MVC错误处理相关的配置内容,在ErrorMvcAutoConfiguration这个类中。以下会分块介绍这个类里面的配置。
在Servlet容器中添加了一个默认的错误页面
因为ErrorMvcAutoConfiguration类实现了EmbeddedServletContainerCustomizer接口,所以可以通过override customize方法来定制Servlet容器。以下代码摘自ErrorMvcAutoConfiguration:
@Value("${error.path:/error}")
private String errorPath = "/error";
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(this.properties.getServletPrefix()
+ this.errorPath));
}
可以看到ErrorMvcAutoConfiguration在容器中,添加了一个错误页面/error。因为这项配置的存在,如果Spring MVC在处理过程抛出异常到Servlet容器,容器会定向到这个错误页面/error。
那么我们有什么可以配置的呢?
- 我们可以配置错误页面的url,/error是默认值,我们可以再application.properties中通过设置error.path的值来配置该页面的url;
- 我们可以提供一个自定义的EmbeddedServletContainerCustomizer,添加更多的错误页面,比如对不同的http status code,使用不同的错误处理页面。就像下面这段代码一样:
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
}
};
}
定义了ErrorAttributes接口,并默认配置了一个DefaultErrorAttributes Bean
以下代码摘自ErrorMvcAutoConfiguration:
@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes();
}
以下代码摘自DefaultErrorAttributes, ErrorAttributes, HandlerExceptionResolver:
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver,
Ordered {
//篇幅原因,忽略类的实现代码。
}
public interface ErrorAttributes {
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace);
public Throwable getError(RequestAttributes requestAttributes);
}
public interface HandlerExceptionResolver {
ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}
这个DefaultErrorAttributes有什么用呢?主要有两个作用:
- 实现了ErrorAttributes接口,具备提供Error Attributes的能力,当处理/error错误页面时,需要从该bean中读取错误信息以供返回;
- 实现了HandlerExceptionResolver接口并具有最高优先级,即DispatcherServlet在doDispatch过程中有异常抛出时,先由DefaultErrorAttributes处理。从下面代码中可以发现,DefaultErrorAttributes在处理过程中,是讲ErrorAttributes保存到了request中。事实上,这是DefaultErrorAttributes能够在后面返回Error Attributes的原因,实现HandlerExceptionResolver接口,是DefaultErrorAttributes实现ErrorAttributes接口的手段。
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
storeErrorAttributes(request, ex);
return null;
}
我们有什么可以配置的呢?
1、我们可以继承DefaultErrorAttributes,修改Error Attributes,比如下面这段代码,去掉了默认存在的error和exception这两个字段,以隐藏敏感信息。
@Bean
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
@Override
public Map<String, Object> getErrorAttributes (RequestAttributes requestAttributes,
boolean includeStackTrace){
Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
errorAttributes.remove("error");
errorAttributes.remove("exception");
return errorAttributes;
}
};
}
- 我们可以自己实现ErrorAttributes接口,实现自己的Error Attributes方案, 只要配置一个类型为ErrorAttributes的bean,默认的DefaultErrorAttributes就不会被配置。
提供并配置了ErrorController和ErrorView
ErrorController和ErrorView提供了对错误页面/error的支持。ErrorMvcAutoConfiguration默认配置了BasicErrorController和WhiteLabelErrorView,以下代码摘自ErrorMvcAutoConfiguration:
@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
return new BasicErrorController(errorAttributes);
}
@Configuration
@ConditionalOnProperty(prefix = "error.whitelabel", name = "enabled", matchIfMissing = true)
@Conditional(ErrorTemplateMissingCondition.class)
protected static class WhitelabelErrorViewConfiguration {
private final SpelView defaultErrorView = new SpelView(
"<html><body><h1>Whitelabel Error Page</h1>"
+ "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"
+ "<div id='created'>${timestamp}</div>"
+ "<div>There was an unexpected error (type=${error}, status=${status}).</div>"
+ "<div>${message}</div></body></html>");
@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(BeanNameViewResolver.class)
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver;
}
}
ErrorController根据Accept头的内容,输出不同格式的错误响应。比如针对浏览器的请求生成html页面,针对其它请求生成json格式的返回。代码如下:
@RequestMapping(value = "${error.path:/error}", produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request) {
return new ModelAndView("error", getErrorAttributes(request, false));
}
@RequestMapping(value = "${error.path:/error}")
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, getTraceParameter(request));
HttpStatus status = getStatus(request);
return new ResponseEntity<Map<String, Object>>(body, status);
}
WhitelabelErrorView则提供了一个默认的白板错误页面。
我们有什么可以配置的呢?
- 我们可以提供自己的名字为error的view,以替换掉默认的白板页面,提供自己想要的样式。
- 我们可以继承BasicErrorController或者干脆自己实现ErrorController接口,用来响应/error这个错误页面请求,可以提供更多类型的错误格式等。
总结
Spring Boot提供了默认的统一错误页面,这是Spring MVC没有提供的。在理解了Spring Boot提供的错误处理相关内容之后,我们可以方便的定义自己的错误返回的格式和内容。不过,如果要实现统一的REST API接口的出错响应,就如这篇文章里的这样,还是要做不少工作的。
Spring Boot异常处理详解的更多相关文章
- Spring Boot 配置文件详解
Spring Boot配置文件详解 Spring Boot提供了两种常用的配置文件,分别是properties文件和yml文件.他们的作用都是修改Spring Boot自动配置的默认值.相对于prop ...
- Spring Boot 注解详解
一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration ...
- Spring Boot配置文件详解-ConfigurationProperties和Value优缺点-(转)好文
文章转自 http://www.cnblogs.com/itdragon/p/8686554.html Spring Boot提供了两种常用的配置文件,分别是properties文件和yml文件.他们 ...
- (转) SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解
springboot采纳了建立生产就绪spring应用程序的观点. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.在一般情况下,我们不需要做太多的配置就能够让spring boot正 ...
- SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解
转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot2-config-file/ 本文出自方志朋的博客 ...
- Spring Boot (九): 微服务应用监控 Spring Boot Actuator 详解
1. 引言 在当前的微服务架构方式下,我们会有很多的服务部署在不同的机器上,相互是通过服务调用的方式进行交互,一个完整的业务流程中间会经过很多个微服务的处理和传递,那么,如何能知道每个服务的健康状况就 ...
- Spring MVC异常处理详解(转)
下图中,我画出了Spring MVC中,跟异常处理相关的主要类和接口. 在Spring MVC中,所有用于处理在请求映射和请求处理过程中抛出的异常的类,都要实现HandlerExceptionReso ...
- Spring MVC异常处理详解 ExceptionHandler good
@ControllerAdvice(basePackageClasses = AcmeController.class) public class AcmeControllerAdvice exten ...
- spring -boot s-tarter 详解
Starter POMs是可以包含到应用中的一个方便的依赖关系描述符集合.你可以获取所有Spring及相关技术的一站式服务,而不需要翻阅示例代码,拷贝粘贴大量的依赖描述符.例如,如果你想使用Sprin ...
随机推荐
- Linux环境下查看历史操作命令及清除方法
在Linux环境中可以通过方向键的上下按键查看近期键入的命令.但这种方法只能一个一个的查看,其实系统提供了查看所有历史命令的方法. 在终端中输入以下命令查看所有命令: history [root@te ...
- 用脚本定时监控SQL Server主从一致性
用脚本定时监控SQL Server主从一致性 首先说一下我们的环境 我们使用的是事务复制,复制是单向的,主服务器和从服务器都在同一个机房,当然不同机房也可以,只需要改一下IP和端口 下面的脚本在我们的 ...
- 微信公共平台开发-(.net实现)5--access_token过期的问题
每次在于微信交互时,都要用到access_token,但是这个值限制的是有时间的,但是access_token,在以后的高级功能里面会经常用到,所以这里不得不这里对前面所讲解的access_token ...
- HTTP基本认证
众所周知,Web使人们可以很方便的访问分布在世界各个角落里信息.但是仅仅是方便还是不够的,并不是所有的信息都适合在互联网上公开访问,我们需要保证只有特定的人才能看到我们的敏感信息并且执行特定的操作. ...
- 基于MVC4+EasyUI的Web开发框架形成之旅--附件上传组件uploadify的使用
大概一年前,我还在用Asp.NET开发一些行业管理系统的时候,就曾经使用这个组件作为文件的上传操作,在随笔<Web开发中的文件上传组件uploadify的使用>中可以看到,Asp.NET中 ...
- [C#进阶系列]专题一:深入解析深拷贝和浅拷贝
一.前言 这个星期参加了一个面试,面试中问到深浅拷贝的区别,然后我就简单了讲述了它们的之间的区别,然后面试官又继续问,如何实现一个深拷贝呢?当时只回答回答了一种方式,就是使用反射,然后面试官提示还可以 ...
- 【Win10】UAP/UWP/通用 开发之 RelativePanel
[Some information relates to pre-released product which may be substantially modified before it's co ...
- Java提高篇(三四)-----fail-fast机制
在JDK的Collection中我们时常会看到类似于这样的话: 例如,ArrayList: 注意,迭代器的快速失败行为无法得到保证,因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证.快速失 ...
- 《OOC》笔记(2)——C语言实现trycatchfinally
本篇就偷个懒吧,实在打不起精神. #ifndef _TRY_THROW_CATCH_H_ #define _TRY_THROW_CATCH_H_ #include <stdio.h> #i ...
- read links July-14
1) http://ruby-hacking-guide.github.io/intro.html It has one part to discuss “Technique to read so ...