在《 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。
那么我们有什么可以设置的呢?
@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有什么用呢?主要有两个浸染:
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
storeErrorAttributes(request, ex);
return null;
}
我们有什么可以设置的呢?
我们可以担任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