本文共 3333 字,大约阅读时间需要 11 分钟。
本节书摘来自异步社区《精通Spring MVC 4》一书中的第1章,第1.7节,作者:【美】Geoffroy Warin著,更多章节内容可以访问云栖社区“异步社区”公众号查看
还记得在没有添加控制器的时候,第一次启动应用吗?当时看到了一个有意思的“Whitelabel Error Page”输出。
错误处理要比看上去更麻烦一些,尤其是在没有web.xml配置文件并且希望应用能够跨Web服务器部署时更是如此。好消息是Spring Boot将会处理这些事情!让我们看一下ErrorMvcAutoConfiguration:
ConditionalOnClass({ Servlet.class, DispatcherServlet.class })@ConditionalOnWebApplication// Ensure this loads before the main WebMvcAutoConfiguration so thatthe error View is// available@AutoConfigureBefore(WebMvcAutoConfiguration.class)@Configurationpublic class ErrorMvcAutoConfiguration implementsEmbeddedServletContainerCustomizer, Ordered { @Value("${error.path:/error}") private String errorPath = "/error"; @Autowired private ServerProperties properties; @Override public int getOrder() { return 0; } @Bean @ConditionalOnMissingBean(value = ErrorAttributes.class, search =SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes() { return new DefaultErrorAttributes(); } @Bean @ConditionalOnMissingBean(value = ErrorController.class, search =SearchStrategy.CURRENT) public BasicErrorController basicErrorController(ErrorAttributeserrorAttributes) { return new BasicErrorController(errorAttributes); } @Override public void customize(ConfigurableEmbeddedServletContainercontainer) { container.addErrorPages(new ErrorPage(this.properties.getServletPrefix() + this.errorPath)); } @Configuration @ConditionalOnProperty(prefix = "error.whitelabel", name ="enabled", matchIfMissing = true) @Conditional(ErrorTemplateMissingCondition.class) protected static class WhitelabelErrorViewConfiguration { private final SpelView defaultErrorView = new SpelView( "Whitelabel Error Page
" + "This application has no explicit mappingfor /error, so you are seeing this as a fallback.
" + "${timestamp}" + "There was an unexpected error(type=${error}, status=${status})." + "${message}"); @Bean(name = "error") @ConditionalOnMissingBean(name = "error") public View defaultErrorView() { return this.defaultErrorView; } // If the user adds @EnableWebMvc then the bean name viewresolver from // WebMvcAutoConfiguration disappears, so add it back in toavoid disappointment. @Bean @ConditionalOnMissingBean(BeanNameViewResolver.class) public BeanNameViewResolver beanNameViewResolver() { BeanNameViewResolver resolver = newBeanNameViewResolver(); resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10); return resolver; } }}
这段配置都做了些什么呢?
定义了一个bean,即DefaultErrorAttributes,它通过特定的属性暴露了有用的错误信息,这些属性包括状态、错误码和相关的栈跟踪信息。
定义了一个BasicErrorController bean,这是一个MVC控制器,负责展现我们所看到的错误页面。允许我们将Spring Boot的whitelabel错误页面设置为无效,这需要将配置文件application.properties中的error.whitelable.enabled设置为false。我们还可以借助模板引擎提供自己的错误页面。例如,它的名字是error.html,ErrorTemplateMissingCondition条件会对此进行检查。在本书后面的内容中,我们将会看到如何恰当地处理错误。至于转码的问题,非常简单的HttpEncodingAutoConfiguration将会负责处理相关的事宜,这是通过提供Spring的CharacterEncodingFilter类来实现的。通过spring.http.encoding.charset配置,我们可以覆盖默认的编码(“UTF-8”),也可以通过spring.http.encoding.enabled禁用这项配置。
转载地址:http://qhall.baihongyu.com/