三种异常页面
- 自定义的错误页面
- SpringBoot的错误页面
- Tomcat的错误页面
- SpringBoot错误处理原理及定制错误页面及错误数据 _彭大坤的博客-CSDN博客_springboot错误页面
SpringBoot——错误处理机制 & 定制错误页面 (源码分析)_Guizy-CSDN博客
异常处理流程
没找到HandlerMapping情况
找HandlerMapping【SimpleUrlHandlerMapping】
当我们请求一个不存在的路径,RequestMappingHandlerMapping没有找到,落到SimpleUrlHandlerMapping上了。
找Handler【ResourceHttpRequestHandler】
通过SimpleUrlHandlerMapping得到ResourceHttpRequestHandler
ResourceHttpRequestHandler设置responseStatus=404:tomcat转到/error页面
ResourceHttpRequestHandler 拦截 /** 所有路径
- 在ResourceHttpRequestHandler.handleRequest 处理时 如果获取不到resource就设置responseStatus为404。
tomcat收到response为404,dispatch到/error页面。
tomcat收到response为404,dispatch到/error页面。
tomcat收到response为404,dispatch到/error页面。
dispatch前端无感知。
/error 找到controller【BasicErrorController】
/error RequestMappingHandlerMapping根据找到BasicErrorController
BasicErrorController处理
Controller中调用ErrorViewResolver(DefaultErrorViewResolver)处理
ErrorViewResolver中处理【判断4xx.html】
依次判断
- error/4xx.html
- resources/error/4xx.html
- static/error/4xx.html
- public/error/4xx.html
没找到ModelAndView,构造一个viewName为error的ModelAndView
路过returnValueHandlers
processDispatchResult
render
ResolveViewName:利用ViewResolver根据名字解析出View
StaticView就是最终显示的View
view.render:显示页面
自定义错误页面
方式一:添加ErrorPage
老:
@Configuration
public class ErrorPageConfig {
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/static/html/500.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/static/html/500.html");
container.addErrorPages(error404Page, error500Page);
}
};
}
}
新:
@Configuration
public class ContainerConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage[] errorPages = new ErrorPage[2];
errorPages[0] = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
errorPages[1] = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
registry.addErrorPages(errorPages);
}
}
方式二:重写名字为Error的View
定义view
public class GunsErrorView implements View {
@Override
public String getContentType() {
return "text/html";
}
@Override
public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
httpServletRequest.getRequestDispatcher("/global/error").forward(httpServletRequest, httpServletResponse);
}
}
view解析将跳转到/global/error(自定义Controller)
配置error view
//bean名称必须为error,
@Bean("error")
public GunsErrorView error() {
return new GunsErrorView();
}
方式三:自定义ErrorViewResolver
ErrorViewResolver在BasicErrorController中被使用。返回ModelAndView。
…