環境:Springboot2.4.11
環境配置
接下來的演示都是基于如下接口進行。
@RestController
@RequestMApping("/exceptions")
public class ExceptionsController {
@GetMapping("/index")
public Object index(int a) {
if (a == 0) {
throw new BusinessException() ;
}
return "exception" ;
}
}
默認錯誤輸出
默認情況下,當請求一個接口發生異常時會有如下兩種情況的錯誤信息提示
- 基于html
- 基于JSON
上面兩個示例通過請求的Accept請求頭設置希望接受的數據類型,得到不同的響應數據類型。
標準web錯誤頁配置
在標準的JAVA web項目中我們一般是在web.xml文件中進行錯誤頁的配置,如下:
<error-page>
<location>/error</location>
</error-page>
如上配置后,如發生了異常以后容器會自動地跳轉到錯誤頁面。
Spring實現原理
在Springboot中沒有web.xml,并且Servlet API也沒有提供相應的API進行錯誤頁的配置。那么在Springboot中又是如何實現錯誤頁的配置呢?
Springboot內置了應用服務,如Tomcat,Undertow,Jetty,默認是Tomcat。那接下來看下基于默認的Tomcat容器錯誤頁是如何進行配置的。
- Servlet Web服務自動配置
@EnableConfigurationProperties(ServerProperties.class)
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,
ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,...})
public class ServletWebServerFactoryAutoConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class })
@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
static class EmbeddedTomcat {
// 這里主要就是配置Web 容器服務,如這里使用的Tomcat
// 注意該類實現了ErrorPageRegistry ,那么也就是說該類可以用來注冊錯誤頁的
@Bean
TomcatServletWebServerFactory tomcatServletWebServerFactory(
ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers,
ObjectProvider<TomcatContextCustomizer> contextCustomizers,
ObjectProvider<TomcatProtocolHandlerCustomizer<?>> protocolHandlerCustomizers) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.getTomcatConnectorCustomizers().addAll(connectorCustomizers.orderedStream().collect(Collectors.toList()));
factory.getTomcatContextCustomizers().addAll(contextCustomizers.orderedStream().collect(Collectors.toList()));
factory.getTomcatProtocolHandlerCustomizers().addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList()));
return factory;
}
}
}
在@Import中只列出了兩個比較重要的
BeanPostProcessorsRegistrar與EmbeddedTomcat
BeanPostProcessorsRegistrar注冊了兩個BeanPostProcessor處理器
public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
if (this.beanFactory == null) {
return;
}
registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class, WebServerFactoryCustomizerBeanPostProcessor::new);
registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class, ErrorPageRegistrarBeanPostProcessor::new);
}
}
通過名稱也能知道
WebServerFactoryCustomizerBeanPostProcessor用來處理Tomcat相關的自定義信息;
ErrorPageRegistrarBeanPostProcessor 這個就是重點了,這個就是用來配置我們的自定義錯誤頁面的。
public class ErrorPageRegistrarBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 這里判斷了當前的bean對象是否是ErrorPageRegistry的實例
// 當前類既然是BeanPostProcessor實例,同時上面注冊了一個TomcatServletWebServerFactory Bean實例
// 那么在實例化TomcatServletWebServerFactory時一定是會調用該BeanPostProcessor處理器的
if (bean instanceof ErrorPageRegistry) {
postProcessBeforeInitialization((ErrorPageRegistry) bean);
}
return bean;
}
// 注冊錯誤頁面
private void postProcessBeforeInitialization(ErrorPageRegistry registry) {
for (ErrorPageRegistrar registrar : getRegistrars()) {
registrar.registerErrorPages(registry);
}
}
private Collection<ErrorPageRegistrar> getRegistrars() {
if (this.registrars == null) {
// Look up does not include the parent context
// 從當前上下文中(比包括父上下文)查找ErrorPageRegistrar Bean對象
this.registrars = new ArrayList<>(this.beanFactory.getBeansOfType(ErrorPageRegistrar.class, false, false).values());
this.registrars.sort(AnnotationAwareOrderComparator.INSTANCE);
this.registrars = Collections.unmodifiableList(this.registrars);
}
return this.registrars;
}
}
注冊錯誤頁面
在上一步中知道了錯誤頁的注冊入口是在一個
ErrorPageRegistrarBeanPostProcessor Bean后處理器中進行注冊的,接下來繼續深入查看這個錯誤頁是如何被注冊的。
接著上一步在
ErrorPageRegistrarBeanPostProcessor中查找ErrorPageRegistrar類型的Bean對象。在另外一個自動配置中(ErrorMvcAutoConfiguration)有注冊ErrorPageRegistrar Bean對象
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, WebMvcProperties.class })
public class ErrorMvcAutoConfiguration {
// 該類是ErrorPageRegistrar子類,那么在注冊錯誤頁的時候注冊的就是該類中生成的錯誤頁信息
static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
private final ServerProperties properties;
private final DispatcherServletPath dispatcherServletPath;
protected ErrorPageCustomizer(ServerProperties properties, DispatcherServletPath dispatcherServletPath) {
this.properties = properties;
this.dispatcherServletPath = dispatcherServletPath;
}
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
// 錯誤頁的地址可以在配置文件中自定義server.error.path進行配置,默認:/error
ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(errorPage);
}
@Override
public int getOrder() {
return 0;
}
}
}
關鍵代碼
// errorPageRegistry對象的實例是TomcatServletWebServerFactory
errorPageRegistry.addErrorPages(errorPage);
TomcatServletWebServerFactory中注冊錯誤頁信息,該類的父類(AbstractConfigurableWebServerFactory)方法中有添加錯誤也的方法
public abstract class AbstractConfigurableWebServerFactory {
private Set<ErrorPage> errorPages = new LinkedHashSet<>();
public void addErrorPages(ErrorPage... errorPages) {
this.errorPages.addAll(Arrays.asList(errorPages));
}
}
這個錯誤頁的注冊到Tomcat容器中又是如何實現的呢?
Tomcat中注冊錯誤頁
接下來看看這個錯誤頁是如何與Tomcat關聯在一起的。
Spring容器最核心的方法是refresh方法
public abstract class AbstractApplicationContext {
public void refresh() {
// ...
// Initialize other special beans in specific context subclasses.
onRefresh();
// ...
}
}
執行onRefresh方法
public class ServletWebServerApplicationContext extends GenericWebApplicationContext {
protected void onRefresh() {
super.onRefresh();
try {
// 創建Tomcat服務
createWebServer();
} catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
private void createWebServer() {
// ...
// 返回應用于創建嵌入的Web服務器的ServletWebServerFactory。默認情況下,此方法在上下文本身中搜索合適的bean。
// 在上面ServletWebServerFactoryAutoConfiguration自動配置中,已經自動的根據當前的環境創建了TomcatServletWebServerFactory對象
ServletWebServerFactory factory = getWebServerFactory();
// 獲取WebServer實例, factory = TomcatServletWebServerFactory
this.webServer = factory.getWebServer(getSelfInitializer());
// ...
}
}
調用
TomcatServletWebServerFactory#getWebServer方法
public class TomcatServletWebServerFactory extends AbstractServletWebServerFactory {
public WebServer getWebServer(ServletContextInitializer... initializers) {
// ...
Tomcat tomcat = new Tomcat();
// ...
// 預處理上下文
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
// ...
// 配置上下文
configureContext(context, initializersToUse);
}
protected void configureContext(Context context, ServletContextInitializer[] initializers) {
TomcatStarter starter = new TomcatStarter(initializers);
// ...
// 在這里就將錯誤的頁面注冊到了tomcat容器中
for (ErrorPage errorPage : getErrorPages()) {
org.Apache.tomcat.util.descriptor.web.ErrorPage tomcatErrorPage = new org.apache.tomcat.util.descriptor.web.ErrorPage();
tomcatErrorPage.setLocation(errorPage.getPath());
tomcatErrorPage.setErrorCode(errorPage.getStatusCode());
tomcatErrorPage.setExceptionType(errorPage.getExceptionName());
context.addErrorPage(tomcatErrorPage);
}
// ...
}
}
到此你就知道了一個錯誤的頁是如何在Springboot中被注冊的。到目前為止我們看到的注冊到tomcat容器中的錯誤頁都是個地址,比如:默認是/error。那這個默認的/error又是怎么提供的接口呢?
默認錯誤頁
在Springboot中默認有個自動配置的錯誤頁,在上面有一個代碼片段你應該注意到了
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties({ ServerProperties.class, WebMvcProperties.class })
public class ErrorMvcAutoConfiguration {
@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(ErrorAttributes errorAttributes, ObjectProvider<ErrorViewResolver> errorViewResolvers) {
return new BasicErrorController(errorAttributes, this.serverProperties.getError(), errorViewResolvers.orderedStream().collect(Collectors.toList()));
}
}
查看這個Controller
// 默認的錯誤頁地址是/error
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity<>(status);
}
Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
return new ResponseEntity<>(body, status);
}
}
這里有兩個方法,分別處理了不同的Accept請求頭。到此你是否真正地明白了Springboot中的錯誤處理的工作原理呢?
完畢!!!