你以为Spring Boot统一异常处理能拦截所有的异常?

开发 架构
通常我们在Spring Boot中设置的统一异常处理只能处理Controller抛出的异常。有些请求还没到Controller就出异常了,而这些异常不能被统一异常捕获,例如Servlet容器的某些异常。

[[396961]]

通常我们在Spring Boot中设置的统一异常处理只能处理Controller抛出的异常。有些请求还没到Controller就出异常了,而这些异常不能被统一异常捕获,例如Servlet容器的某些异常。今天我在项目开发中就遇到了一个,这让我很不爽,因为它返回的错误信息格式不能统一处理,我决定找个方案解决这个问题。

ErrorPageFilter

Whitelabel Error Page

这类图相信大家没少见,Spring Boot 只要出错,体现在页面上的就是这个。如果你用Postman之类的测试出了异常则是:

  1.   "timestamp""2021-04-29T22:45:33.231+0000"
  2.   "status": 500, 
  3.   "message""Internal Server Error"
  4.   "path""foo/bar" 

这个是怎么实现的呢?Spring Boot在启动时会注册一个ErrorPageFilter,当Servlet发生异常时,该过滤器就会拦截处理,将异常根据不同的策略进行处理:当异常已经在处理的话直接处理,否则转发给对应的错误页面。有兴趣的可以去看下源码,逻辑不复杂,这里就不贴了。

另外当一个 Servlet 抛出一个异常时,处理异常的Servlet可以从HttpServletRequest里面得到几个属性,如下:

异常属性

我们可以从上面的几个属性中获取异常的详细信息。

默认错误页面

通常Spring Boot出现异常默认会跳转到/error进行处理,而/error的相关逻辑则是由BasicErrorController实现的。

  1. @Controller 
  2. @RequestMapping("${server.error.path:${error.path:/error}}"
  3. public class BasicErrorController extends AbstractErrorController { 
  4.     //返回错误页面 
  5.   @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) 
  6.  public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { 
  7.   HttpStatus status = getStatus(request); 
  8.   Map<String, Object> model = Collections 
  9.     .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); 
  10.   response.setStatus(status.value()); 
  11.   ModelAndView modelAndView = resolveErrorView(request, response, status, model); 
  12.   return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); 
  13.  } 
  14.     // 返回json 
  15.  @RequestMapping 
  16.  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { 
  17.   HttpStatus status = getStatus(request); 
  18.   if (status == HttpStatus.NO_CONTENT) { 
  19.    return new ResponseEntity<>(status); 
  20.   } 
  21.   Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); 
  22.   return new ResponseEntity<>(body, status); 
  23.  }   
  24. // 其它省略 

而对应的配置:

  1. @Bean 
  2. @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT
  3. public BasicErrorController basicErrorController(ErrorAttributes errorAttributes, 
  4.       ObjectProvider<ErrorViewResolver> errorViewResolvers) { 
  5.    return new BasicErrorController(errorAttributes, this.serverProperties.getError(), 
  6.          errorViewResolvers.orderedStream().collect(Collectors.toList())); 

所以我们只需要重新实现一个ErrorController并注入Spring IoC就可以替代默认的处理机制。而且我们可以很清晰的发现这个BasicErrorController不但是ErrorController的实现而且是一个控制器,如果我们让控制器的方法抛异常,肯定可以被自定义的统一异常处理。所以我对BasicErrorController进行了改造:

  1. @Controller 
  2. @RequestMapping("${server.error.path:${error.path:/error}}"
  3. public class ExceptionController extends AbstractErrorController { 
  4.  
  5.  
  6.     public ExceptionController(ErrorAttributes errorAttributes) { 
  7.         super(errorAttributes); 
  8.     } 
  9.  
  10.  
  11.     @Override 
  12.     @Deprecated 
  13.     public String getErrorPath() { 
  14.         return null
  15.     } 
  16.  
  17.     @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) 
  18.     public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { 
  19.         throw new RuntimeException(getErrorMessage(request)); 
  20.     } 
  21.  
  22.     @RequestMapping 
  23.     public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { 
  24.         throw new RuntimeException(getErrorMessage(request)); 
  25.     } 
  26.  
  27.     private String getErrorMessage(HttpServletRequest request) { 
  28.         Object code = request.getAttribute("javax.servlet.error.status_code"); 
  29.         Object exceptionType = request.getAttribute("javax.servlet.error.exception_type"); 
  30.         Object message = request.getAttribute("javax.servlet.error.message"); 
  31.         Object path = request.getAttribute("javax.servlet.error.request_uri"); 
  32.         Object exception = request.getAttribute("javax.servlet.error.exception"); 
  33.  
  34.         return String.format("code: %s,exceptionType: %s,message: %s,path: %s,exception: %s"
  35.                 code, exceptionType, message, path, exception); 
  36.     } 

 

直接抛异常,简单省力!凡是这里捕捉的到的异常大部分还没有经过Controller,我们通过ExceptionController中继也让这些异常被统一处理,保证整个应用的异常处理对外保持一个统一的门面。

 

责任编辑:武晓燕 来源: 码农小胖哥
相关推荐

2017-05-18 14:14:25

过滤器Spring ClouZuul

2022-04-08 16:27:48

SpringBoot异常处理

2017-05-19 15:13:05

过滤器Spring ClouZuul

2017-07-31 15:47:50

Zuul统一处理

2023-11-28 14:32:04

2021-04-20 10:50:38

Spring Boot代码Java

2019-08-22 14:02:00

Spring BootRestful APIJava

2023-09-24 13:55:42

Spring应用程序

2022-10-26 07:14:25

Spring 6Spring业务

2022-05-30 08:03:06

后端参数校验异常处理

2011-05-24 09:22:44

Spring3异常处理

2023-07-10 08:00:13

架构Rest返回值

2020-03-16 17:20:02

异常处理Spring Boot

2023-11-30 07:00:56

SpringBoot处理器

2020-03-11 08:00:00

.NET异常处理编程语言

2022-03-15 21:38:29

sentry微服务监控

2023-12-11 14:19:00

Java程序异常

2022-05-07 10:09:01

开发Java日志

2012-12-21 10:48:20

Java异常

2013-08-22 17:10:09

.Net异常处理
点赞
收藏

51CTO技术栈公众号