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。

那么我们有什么可以配置的呢?

  1. 我们可以配置错误页面的url,/error是默认值,我们可以再application.properties中通过设置error.path的值来配置该页面的url;
  2. 我们可以提供一个自定义的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有什么用呢?主要有两个作用:

  1. 实现了ErrorAttributes接口,具备提供Error Attributes的能力,当处理/error错误页面时,需要从该bean中读取错误信息以供返回;
  2. 实现了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;
}
};
}
  1. 我们可以自己实现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则提供了一个默认的白板错误页面。

我们有什么可以配置的呢?

  1. 我们可以提供自己的名字为error的view,以替换掉默认的白板页面,提供自己想要的样式。
  2. 我们可以继承BasicErrorController或者干脆自己实现ErrorController接口,用来响应/error这个错误页面请求,可以提供更多类型的错误格式等。

总结

Spring Boot提供了默认的统一错误页面,这是Spring MVC没有提供的。在理解了Spring Boot提供的错误处理相关内容之后,我们可以方便的定义自己的错误返回的格式和内容。不过,如果要实现统一的REST API接口的出错响应,就如这篇文章里的这样,还是要做不少工作的。

Spring Boot异常处理详解的更多相关文章

  1. Spring Boot 配置文件详解

    Spring Boot配置文件详解 Spring Boot提供了两种常用的配置文件,分别是properties文件和yml文件.他们的作用都是修改Spring Boot自动配置的默认值.相对于prop ...

  2. Spring Boot 注解详解

    一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration ...

  3. Spring Boot配置文件详解-ConfigurationProperties和Value优缺点-(转)好文

    文章转自 http://www.cnblogs.com/itdragon/p/8686554.html Spring Boot提供了两种常用的配置文件,分别是properties文件和yml文件.他们 ...

  4. (转) SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解

    springboot采纳了建立生产就绪spring应用程序的观点. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.在一般情况下,我们不需要做太多的配置就能够让spring boot正 ...

  5. SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot2-config-file/ 本文出自方志朋的博客 ...

  6. Spring Boot (九): 微服务应用监控 Spring Boot Actuator 详解

    1. 引言 在当前的微服务架构方式下,我们会有很多的服务部署在不同的机器上,相互是通过服务调用的方式进行交互,一个完整的业务流程中间会经过很多个微服务的处理和传递,那么,如何能知道每个服务的健康状况就 ...

  7. Spring MVC异常处理详解(转)

    下图中,我画出了Spring MVC中,跟异常处理相关的主要类和接口. 在Spring MVC中,所有用于处理在请求映射和请求处理过程中抛出的异常的类,都要实现HandlerExceptionReso ...

  8. Spring MVC异常处理详解 ExceptionHandler good

    @ControllerAdvice(basePackageClasses = AcmeController.class) public class AcmeControllerAdvice exten ...

  9. spring -boot s-tarter 详解

    Starter POMs是可以包含到应用中的一个方便的依赖关系描述符集合.你可以获取所有Spring及相关技术的一站式服务,而不需要翻阅示例代码,拷贝粘贴大量的依赖描述符.例如,如果你想使用Sprin ...

随机推荐

  1. poj 2481 - Cows(树状数组)

    看的人家的思路,没有理解清楚,,, 结果一直改一直交,,wa了4次才交上,,, 注意: 为了使用树状数组,我们要按照e从大到小排序.但s要从小到大.(我开始的时候错在这里了) 代码如下: #inclu ...

  2. android知识杂记(二)

    记录项目中的android零碎知识点,用以备忘. AsyncQueryHandler 继承与handler,可以用于处理增删改(ContentProvider提供的数据) 例如:query = new ...

  3. Java设计模式9:代理模式

    代理模式 代理模式的定义很简单:给某一对象提供一个代理对象,并由代理对象控制对原对象的引用. 代理模式的结构 有些情况下,一个客户不想活着不能够直接引用一个对象,可以通过代理对象在客户端和目标对象之间 ...

  4. Aoite 系列 目录

    介绍 本项目从2009年孵化(V->Sofire->Aoite),至今已度过5个年头.一直在优化,一直在重构,一直在商用.有十分完整的单元测试用例.可以放心使用. Aoite on 博客园 ...

  5. UWP 统一平台开发介绍

    什么是UWP? 很多程序员都有一个梦想:希望自己开发的软件能够轻而易举的在所有平台上运行,而不是把同样的需求,用不同的技术.工具重新开发才能够运行在所有平台上.这就是跨平台,很多软件从业者都在为这个梦 ...

  6. 最全数据结构详述: List VS IEnumerable VS IQueryable VS ICollection VS IDictionary

    本文对常用的数据结构详述:Array, ArrayList,List,IList,ICollection, Stack, Queue, HashTable, Dictionary, IQueryabl ...

  7. Linux-磁盘管理小结

    这篇博文主要总结了Linux磁盘的一些操作,主要是硬盘的加载,分区(MBR分区和GPT分区),分区的挂载,以及swap分区的加载设置. 基础命令 df查看磁盘分区使用状况 -l //仅显示本地磁盘(默 ...

  8. swift 加载 storyboard 里的UIViewController

    let storyBoard:UIStoryboard! = UIStoryboard(name: "Main", bundle: nil) let deskVC:DeskView ...

  9. PDO预处理

    方法:bool PDOStatement::execute ([ array $input_parameters ] ) 1.PDOStatement::execute不使用参数 01)单个绑定值(P ...

  10. position格式布局

    布局大体分为: 位置--position 绝对坐标 absolute 绝对定位的元素 不受其他位置影响 可通过z-index进行层次分级 body来定位自己 相对坐标 设置  top和left之后 r ...