文章目录
1. 引入
在使用SpringBoot项目后,当程序在运行过程中遇到错误,如果配置了模板引擎,那么模板引擎会自动的返回默认解析的结果。如果是浏览器请求访问会放回错误页面;如果是客户端的请求,则会返回json格式的相关信息。不同来源的请求的识别是根据Request Headers中的accept属性中的内容:
- 浏览器:
text/html - 客户端:
"*/*"
2. 错误处理机制分析
那么Spring Boot是如何来处理出现的错误的呢?下面我们从Spring Boot中和错误机制处理相关的源码来看一下。Spring Boot对于错误的处理依赖于错误处理的自动配置ErrorMvcAutoConfiguration,它的源码如下:
package org.springframework.boot.autoconfigure.web;
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
// Load before the main WebMvcAutoConfiguration so that the error View is available
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties(ResourceProperties.class)
public class ErrorMvcAutoConfiguration {}
它被@Configuration注解修饰,表示它是一个配置类。其中最为重要的是通过@Bean给ioc容器中添加了四个组件:
-
DefaultErrorAttributes:
@Bean @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes() { return new DefaultErrorAttributes(); } 它其中返回的是一个DefaultErrorAttributes实例,DefaultErrorAttributes类包含如下方法:
其中
getErrorAttributes()源码如下:@Order(Ordered.HIGHEST_PRECEDENCE) public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered { @Override public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>(); // 获取错误相关的信息并返回 errorAttributes.put("timestamp", new Date()); addStatus(errorAttributes, requestAttributes); addErrorDetails(errorAttributes, requestAttributes, includeStackTrace); addPath(errorAttributes, requestAttributes); return errorAttributes; } }getErrorAttributes()方法中首先定义了一个Map类型的errorAttributes,它的键是错误信息的名字,如时间戳等,对应的值为相关的错误信息,然后返回errorAttributes -
BasicErrorController:它是一个基本的错误处理器,用于处理默认的/error下的请求,源码为:
@Bean @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { return new BasicErrorController(errorAttributes, this.serverProperties.getError(),this.errorViewResolvers); }BasicErrorController的定义为:
@Controller @RequestMapping("${server.error.path:${error.path:/error}}") public class BasicErrorController extends AbstractErrorController {//产生html类型的数据;浏览器发送的请求来到这个方法处理 @RequestMapping(produces = "text/html") public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { // 获取错误的状态码 HttpStatus status = getStatus(request); Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes( request, isIncludeStackTrace(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); // 通过错误视图解析来决定将哪个页面作为错误页面,包含页面地址和页面内容 ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView == null ? new ModelAndView("error", model) : modelAndView); } // 产生json数据,其他客户端的错误请求用这个方法处理 @RequestMapping @ResponseBody public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); // 最后返回的是一个Map类型的ResponseEntity return new ResponseEntity<Map<String, Object>>(body, status); }其中
resolveErrorView()的定义如下:protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) { // 遍历所有的错误视图解析器,调用其resolveErrorView方法处理 for (ErrorViewResolver resolver : this.errorViewResolvers) { ModelAndView modelAndView = resolver.resolveErrorView(request, status, model); // 如果有相关的解析器处理,返回处理后的modelAndView实例 if (modelAndView != null) { return modelAndView; } } // 否则返回空 return null; } -
ErrorPageCustomizer:表示错误页面的定制化器,源码如下
@Bean public ErrorPageCustomizer errorPageCustomizer() { return new ErrorPageCustomizer(this.serverProperties); }其中ErrorPageCustomizer是ErrorMvcAutoConfiguration的一个静态内部类,定义如下:
private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered { private final ServerProperties properties; protected ErrorPageCustomizer(ServerProperties properties) { this.properties = properties; } @Override public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { ErrorPage errorPage = new ErrorPage(this.properties.getServletPrefix() + this.properties.getError().getPath()); errorPageRegistry.addErrorPages(errorPage); } @Override public int getOrder() { return 0; } }它是ErrorPageRegistrar接口的唯一实现类。其中
getPath()来获取需要解析的错误页面路径,找到它的定义,如下:public class ErrorProperties { /** * Path of the error controller. */ @Value("${error.path:/error}") private String path = "/error"; /** * When to include a "stacktrace" attribute. */ private IncludeStacktrace includeStacktrace = IncludeStacktrace.NEVER; public String getPath() { return this.path; } }最终它会去类路径的"/error"下找对应的错误页面
-
DefaultErrorViewResolver:默认的错误视图解析器
@Configuration static class DefaultErrorViewResolverConfiguration { private final ApplicationContext applicationContext; private final ResourceProperties resourceProperties; DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext, ResourceProperties resourceProperties) { this.applicationContext = applicationContext; this.resourceProperties = resourceProperties; } @Bean @ConditionalOnBean(DispatcherServlet.class) @ConditionalOnMissingBean public DefaultErrorViewResolver conventionErrorViewResolver() { return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties); } }@Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { ModelAndView modelAndView = resolve(String.valueOf(status), model); if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) { modelAndView = resolve(SERIES_VIEWS.get(status.series()), model); } return modelAndView; } private ModelAndView resolve(String viewName, Map<String, Object> model) { // 默认Spring Boot可以去找到一个页面? error/404 String errorViewName = "error/" + viewName; // 模板引擎可以解析这个页面就用模板引擎解析 TemplateAvailabilityProvider provider = this.templateAvailabilityProviders .getProvider(errorViewName, this.applicationContext); // 模板引擎可用的请款下返回到errorViewName指定的视图地址 if (provider != null) { return new ModelAndView(errorViewName, model); } // 模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html return resolveResource(errorViewName, model); }
上述几个组件所经历的步骤为:一旦系统出现4xx或是5xx之类的错误,ErrorPageCustomizer就会生效,然后来到/error请求,这个请求会被BasicErrorController处理,具体相应哪个页面又由DefaultErrorViewResolve解析得到,其中具体的错误信息都保存在DefaultErrorAttributes中。
3. 错误响应定制
3.1 定制错误页面
由上面的分析可知,当系统出现错误时,Spring Boot默认是去类路径下的/error请求。对应的请求为error/状态码,如果将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的/error文件夹下,发生此状态码的错误就会来到对应的页面。
当需要定义错误页面时,可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)。其中从错误页面可以获取到的信息有:
- timestamp:时间戳
- status:状态码
- error:错误提示
- exception:异常对象
- message:异常消息
- errors:JSR303数据校验的错误都在这里
如果模板引擎具体的/error下有就是用对应的页面;如果没有,则去项目的静态资源文件夹下找;如果前面的路径下都没有,使用Spring Boot默认的错误提示页面。
3.2 定制错误json数据
-
自定义异常处理和返回定制的json数据
public class UserNotExistException extends RuntimeException { public UserNotExistException() { super("用户不存在"); } }@ControllerAdvice public class MyExceptionHandler { @ResponseBody @ExceptionHandler(UserNotExistException.class) public Map<String,Object> handleException(Exception e){ Map<String,Object> map = new HashMap<>(); map.put("code","user.notexist"); map.put("message",e.getMessage()); return map; } } -
转发到/error进行自适应响应效果处理
@ExceptionHandler(UserNotExistException.class) public String handleException(Exception e, HttpServletRequest request){ Map<String,Object> map = new HashMap<>(); //传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程 request.setAttribute("javax.servlet.error.status_code",500); map.put("code","user.notexist"); map.put("message",e.getMessage()); //转发到/error return "forward:/error"; } -
将定制数据携带出去:出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由
getErrorAttributes()得到。getErrorAttributes()是AbstractErrorController规定的方法,AbstractErrorController是ErrorController接口的实现类。
为了使用定制的错误响应,要进行如下步骤:
-
编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中
-
页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到。容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;同样也可以自定义ErrorAttributes,通过
getErrorAttributes()同样可以获取到。//给容器中加入我们自己定义的ErrorAttributes @Component public class MyErrorAttributes extends DefaultErrorAttributes { //返回值的map就是页面和json能获取的所有字段 @Override public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace); map.put("company", "Forlogen"); //我们的异常处理器携带的数据 Map<String, Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0); map.put("ext", ext); return map; } }