经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot 错误处理机制与自定义错误处理实现详解
来源:jb51  时间:2018/11/25 19:39:12  对本文有异议

【1】SpringBoot的默认错误处理

① 浏览器访问

请求头如下:

② 使用“PostMan”访问

  1. {
  2. "timestamp": 1529479254647,
  3. "status": 404,
  4. "error": "Not Found",
  5. "message": "No message available",
  6. "path": "/aaa1"
  7. }

请求头如下:

总结:如果是浏览器访问,则SpringBoot默认返回错误页面;如果是其他客户端访问,则默认返回JSON数据。

【2】默认错误处理原理

SpringBoot默认配置了许多xxxAutoConfiguration,这里我们找ErrorMvcAutoConfiguration。

其注册部分组件如下:

① DefaultErrorAttributes

  1. @Bean
  2. @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
  3. public DefaultErrorAttributes errorAttributes() {
  4. return new DefaultErrorAttributes();
  5. }

跟踪其源码如下:

  1. public class DefaultErrorAttributes
  2. implements ErrorAttributes, HandlerExceptionResolver, Ordered {
  3.  
  4. private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName()
  5. + ".ERROR";
  6.  
  7. @Override
  8. public int getOrder() {
  9. return Ordered.HIGHEST_PRECEDENCE;
  10. }
  11.  
  12. @Override
  13. public ModelAndView resolveException(HttpServletRequest request,
  14. HttpServletResponse response, Object handler, Exception ex) {
  15. storeErrorAttributes(request, ex);
  16. return null;
  17. }
  18.  
  19. private void storeErrorAttributes(HttpServletRequest request, Exception ex) {
  20. request.setAttribute(ERROR_ATTRIBUTE, ex);
  21. }
  22.  
  23. @Override
  24. public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
  25. boolean includeStackTrace) {
  26. Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
  27. errorAttributes.put("timestamp", new Date());
  28. addStatus(errorAttributes, requestAttributes);
  29. addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
  30. addPath(errorAttributes, requestAttributes);
  31. return errorAttributes;
  32. }
  33.  
  34. private void addStatus(Map<String, Object> errorAttributes,
  35. RequestAttributes requestAttributes) {
  36. Integer status = getAttribute(requestAttributes,
  37. "javax.servlet.error.status_code");
  38. if (status == null) {
  39. errorAttributes.put("status", 999);
  40. errorAttributes.put("error", "None");
  41. return;
  42. }
  43. errorAttributes.put("status", status);
  44. try {
  45. errorAttributes.put("error", HttpStatus.valueOf(status).getReasonPhrase());
  46. }
  47. catch (Exception ex) {
  48. // Unable to obtain a reason
  49. errorAttributes.put("error", "Http Status " + status);
  50. }
  51. }
  52.  
  53. private void addErrorDetails(Map<String, Object> errorAttributes,
  54. RequestAttributes requestAttributes, boolean includeStackTrace) {
  55. Throwable error = getError(requestAttributes);
  56. if (error != null) {
  57. while (error instanceof ServletException && error.getCause() != null) {
  58. error = ((ServletException) error).getCause();
  59. }
  60. errorAttributes.put("exception", error.getClass().getName());
  61. addErrorMessage(errorAttributes, error);
  62. if (includeStackTrace) {
  63. addStackTrace(errorAttributes, error);
  64. }
  65. }
  66. Object message = getAttribute(requestAttributes, "javax.servlet.error.message");
  67. if ((!StringUtils.isEmpty(message) || errorAttributes.get("message") == null)
  68. && !(error instanceof BindingResult)) {
  69. errorAttributes.put("message",
  70. StringUtils.isEmpty(message) ? "No message available" : message);
  71. }
  72. }
  73.  
  74. private void addErrorMessage(Map<String, Object> errorAttributes, Throwable error) {
  75. BindingResult result = extractBindingResult(error);
  76. if (result == null) {
  77. errorAttributes.put("message", error.getMessage());
  78. return;
  79. }
  80. if (result.getErrorCount() > 0) {
  81. errorAttributes.put("errors", result.getAllErrors());
  82. errorAttributes.put("message",
  83. "Validation failed for object='" + result.getObjectName()
  84. + "'. Error count: " + result.getErrorCount());
  85. }
  86. else {
  87. errorAttributes.put("message", "No errors");
  88. }
  89. }
  90.  
  91. private BindingResult extractBindingResult(Throwable error) {
  92. if (error instanceof BindingResult) {
  93. return (BindingResult) error;
  94. }
  95. if (error instanceof MethodArgumentNotValidException) {
  96. return ((MethodArgumentNotValidException) error).getBindingResult();
  97. }
  98. return null;
  99. }
  100.  
  101. private void addStackTrace(Map<String, Object> errorAttributes, Throwable error) {
  102. StringWriter stackTrace = new StringWriter();
  103. error.printStackTrace(new PrintWriter(stackTrace));
  104. stackTrace.flush();
  105. errorAttributes.put("trace", stackTrace.toString());
  106. }
  107.  
  108. private void addPath(Map<String, Object> errorAttributes,
  109. RequestAttributes requestAttributes) {
  110. String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri");
  111. if (path != null) {
  112. errorAttributes.put("path", path);
  113. }
  114. }
  115.  
  116. @Override
  117. public Throwable getError(RequestAttributes requestAttributes) {
  118. Throwable exception = getAttribute(requestAttributes, ERROR_ATTRIBUTE);
  119. if (exception == null) {
  120. exception = getAttribute(requestAttributes, "javax.servlet.error.exception");
  121. }
  122. return exception;
  123. }
  124.  
  125. @SuppressWarnings("unchecked")
  126. private <T> T getAttribute(RequestAttributes requestAttributes, String name) {
  127. return (T) requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
  128. }
  129.  
  130. }

即,填充错误数据!

② BasicErrorController

  1. @Bean
  2. @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
  3. public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
  4. return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
  5. this.errorViewResolvers);
  6. }

跟踪其源码:

  1. @Controller
  2. @RequestMapping("${server.error.path:${error.path:/error}}")
  3. public class BasicErrorController extends AbstractErrorController {
  4. //产生html类型的数据;浏览器发送的请求来到这个方法处理
  5. @RequestMapping(produces = "text/html")
  6. public ModelAndView errorHtml(HttpServletRequest request,
  7. HttpServletResponse response) {
  8. HttpStatus status = getStatus(request);
  9. Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
  10. request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
  11. response.setStatus(status.value());
  12. //去哪个页面作为错误页面;包含页面地址和页面内容
  13. ModelAndView modelAndView = resolveErrorView(request, response, status, model);
  14. return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
  15. }
  16. //产生json数据,其他客户端来到这个方法处理;
  17. @RequestMapping
  18. @ResponseBody
  19. public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
  20. Map<String, Object> body = getErrorAttributes(request,
  21. isIncludeStackTrace(request, MediaType.ALL));
  22. HttpStatus status = getStatus(request);
  23. return new ResponseEntity<Map<String, Object>>(body, status);
  24. }
  25. //...
  26. }

其中 resolveErrorView(request, response, status, model);方法跟踪如下:

  1. public abstract class AbstractErrorController implements ErrorController {
  2. protected ModelAndView resolveErrorView(HttpServletRequest request,
  3. HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
  4. //拿到所有的错误视图解析器
  5. for (ErrorViewResolver resolver : this.errorViewResolvers) {
  6. ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
  7. if (modelAndView != null) {
  8. return modelAndView;
  9. }
  10. }
  11. return null;
  12. }
  13. //...
  14. }

③ ErrorPageCustomizer

  1. @Bean
  2. public ErrorPageCustomizer errorPageCustomizer() {
  3. return new ErrorPageCustomizer(this.serverProperties);
  4. }

跟踪其源码:

  1. @Override
  2. public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
  3. ErrorPage errorPage = new ErrorPage(this.properties.getServletPrefix()
  4. + this.properties.getError().getPath());
  5. errorPageRegistry.addErrorPages(errorPage);
  6. }
  7. //getPath()->go on
  8. /**
  9. * Path of the error controller.
  10. */
  11. @Value("${error.path:/error}")
  12. private String path = "/error";

即,系统出现错误以后来到error请求进行处理(web.xml注册的错误页面规则)。

④ DefaultErrorViewResolver

  1. @Bean
  2. @ConditionalOnBean(DispatcherServlet.class)
  3. @ConditionalOnMissingBean
  4. public DefaultErrorViewResolver conventionErrorViewResolver() {
  5. return new DefaultErrorViewResolver(this.applicationContext,
  6. this.resourceProperties);
  7. }

跟踪其源码:

  1. public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {
  2.  
  3. private static final Map<Series, String> SERIES_VIEWS;
  4. //错误状态码
  5. static {
  6. Map<Series, String> views = new HashMap<Series, String>();
  7. views.put(Series.CLIENT_ERROR, "4xx");
  8. views.put(Series.SERVER_ERROR, "5xx");
  9. SERIES_VIEWS = Collections.unmodifiableMap(views);
  10. }
  11. //...
  12. @Override
  13. public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status,
  14. Map<String, Object> model) {
  15. // 这里如果没有拿到精确状态码(如404)的视图,则尝试拿4XX(或5XX)的视图
  16. ModelAndView modelAndView = resolve(String.valueOf(status), model);
  17. if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
  18. modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
  19. }
  20. return modelAndView;
  21. }
  22.  
  23. private ModelAndView resolve(String viewName, Map<String, Object> model) {
  24. //默认SpringBoot可以去找到一个页面? error/404||error/4xx
  25. String errorViewName = "error/" + viewName;
  26. //模板引擎可以解析这个页面地址就用模板引擎解析
  27. TemplateAvailabilityProvider provider = this.templateAvailabilityProviders
  28. .getProvider(errorViewName, this.applicationContext);
  29. if (provider != null) {
  30. //模板引擎可用的情况下返回到errorViewName指定的视图地址
  31. return new ModelAndView(errorViewName, model);
  32. }
  33. //模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
  34. return resolveResource(errorViewName, model);
  35. }
  36.  
  37. private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
  38. //从静态资源文件夹下面找错误页面
  39. for (String location : this.resourceProperties.getStaticLocations()) {
  40. try {
  41. Resource resource = this.applicationContext.getResource(location);
  42. resource = resource.createRelative(viewName + ".html");
  43. if (resource.exists()) {
  44. return new ModelAndView(new HtmlResourceView(resource), model);
  45. }
  46. }
  47. catch (Exception ex) {
  48. }
  49. }
  50. return null;
  51. }

总结如下:

一但系统出现4xx或者5xx之类的错误,ErrorPageCustomizer就会生效(定制错误的响应规则),就会来到/error请求,然后被BasicErrorController处理返回ModelAndView或者JSON。

【3】定制错误响应

① 定制错误响应页面

1)有模板引擎的情况下

error/状态码–将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的error文件夹下,发生此状态码的错误就会来到 对应的页面。

我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)。

如下图所示:

页面能获取的信息;

timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里

2)没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找。

3)以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面。

WebMVCAutoConfiguration源码如下:

  1. @Configuration
  2. @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
  3. @Conditional(ErrorTemplateMissingCondition.class)
  4. protected static class WhitelabelErrorViewConfiguration {
  5.  
  6. private final SpelView defaultErrorView = new SpelView(
  7. "<html><body><h1>Whitelabel Error Page</h1>"
  8. + "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"
  9. + "<div id='created'>${timestamp}</div>"
  10. + "<div>There was an unexpected error (type=${error}, status=${status}).</div>"
  11. + "<div>${message}</div></body></html>");
  12.  
  13. @Bean(name = "error")
  14. @ConditionalOnMissingBean(name = "error")
  15. public View defaultErrorView() {
  16. return this.defaultErrorView;
  17. }
  18.  
  19. // If the user adds @EnableWebMvc then the bean name view resolver from
  20. // WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.
  21. @Bean
  22. @ConditionalOnMissingBean(BeanNameViewResolver.class)
  23. public BeanNameViewResolver beanNameViewResolver() {
  24. BeanNameViewResolver resolver = new BeanNameViewResolver();
  25. resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
  26. return resolver;
  27. }
  28.  
  29. }

② 定制错误响应数据

第一种,使用SpringMVC的异常处理器

  1. @ControllerAdvice
  2. public class MyExceptionHandler {
  3.  
  4. //浏览器客户端返回的都是json
  5. @ResponseBody
  6. @ExceptionHandler(UserNotExistException.class)
  7. public Map<String,Object> handleException(Exception e){
  8. Map<String,Object> map = new HashMap<>();
  9. map.put("code","user.notexist");
  10. map.put("message",e.getMessage());
  11. return map;
  12. }
  13. }

这样无论浏览器还是PostMan返回的都是JSON!

第二种,转发到/error请求进行自适应效果处理

  1. @ExceptionHandler(UserNotExistException.class)
  2. public String handleException(Exception e, HttpServletRequest request){
  3. Map<String,Object> map = new HashMap<>();
  4. //传入我们自己的错误状态码 4xx 5xx
  5. /**
  6. * Integer statusCode = (Integer) request
  7. .getAttribute("javax.servlet.error.status_code");
  8. */
  9. request.setAttribute("javax.servlet.error.status_code",500);
  10. map.put("code","user.notexist");
  11. map.put("message","用户出错啦");
  12. //转发到/error
  13. return "forward:/error";
  14. }

但是此时没有将自定义 code message传过去!

第三种,注册MyErrorAttributes继承自DefaultErrorAttributes(推荐)

从第【2】部分(默认错误处理原理)中知道错误数据都是通过DefaultErrorAttributes.getErrorAttributes()方法获取,如下所示:

  1. @Override
  2. public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
  3. boolean includeStackTrace) {
  4. Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
  5. errorAttributes.put("timestamp", new Date());
  6. addStatus(errorAttributes, requestAttributes);
  7. addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
  8. addPath(errorAttributes, requestAttributes);
  9. return errorAttributes;
  10. }

我们可以编写一个MyErrorAttributes继承自DefaultErrorAttributes重写其getErrorAttributes方法将我们的错误数据添加进去。

示例如下:

  1. //给容器中加入我们自己定义的ErrorAttributes
  2. @Component
  3. public class MyErrorAttributes extends DefaultErrorAttributes {
  4.  
  5. //返回值的map就是页面和json能获取的所有字段
  6. @Override
  7. public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
  8. //DefaultErrorAttributes的错误数据
  9. Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
  10. map.put("company","SpringBoot");
  11. //我们的异常处理器携带的数据
  12. Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
  13. map.put("ext",ext);
  14. return map;
  15. }
  16. }

异常处理器修改如下:

  1. @ExceptionHandler(UserNotExistException.class)
  2. public String handleException(Exception e, HttpServletRequest request){
  3. Map<String,Object> map = new HashMap<>();
  4. //传入我们自己的错误状态码 4xx 5xx
  5. /**
  6. * Integer statusCode = (Integer) request
  7. .getAttribute("javax.servlet.error.status_code");
  8. */
  9. request.setAttribute("javax.servlet.error.status_code",500);
  10. map.put("code","user.notexist");
  11. map.put("message","用户出错啦");
  12. //将自定义错误数据放入request中
  13. request.setAttribute("ext",map);
  14. //转发到/error
  15. return "forward:/error";
  16. }

5xx.html页面代码如下:

  1. //...
  2. <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
  3. <h1>status:[[${status}]]</h1>
  4. <h2>timestamp:[[${timestamp}]]</h2>
  5. <h2>exception:[[${exception}]]</h2>
  6. <h2>message:[[${message}]]</h2>
  7. <h2>ext:[[${ext.code}]]</h2>
  8. <h2>ext:[[${ext.message}]]</h2>
  9. </main>
  10. //...

浏览器测试效果如下:

Postman测试效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号