您现在的位置是:亿华云 > 系统运维
你以为Spring Boot统一异常处理能拦截所有的异常?
亿华云2025-10-09 12:51:00【系统运维】9人已围观
简介通常我们在Spring Boot中设置的统一异常处理只能处理Controller抛出的异常。有些请求还没到Controller就出异常了,而这些异常不能被统一异常捕获,例如Servlet容器的某些异常
通常我们在Spring Boot中设置的异常有的异常统一异常处理只能处理Controller抛出的异常。有些请求还没到Controller就出异常了,处理而这些异常不能被统一异常捕获,异常有的异常例如Servlet容器的处理某些异常。今天我在项目开发中就遇到了一个,异常有的异常这让我很不爽,处理因为它返回的异常有的异常错误信息格式不能统一处理,我决定找个方案解决这个问题。处理
ErrorPageFilter
Whitelabel Error Page
这类图相信大家没少见,异常有的异常Spring Boot 只要出错,处理体现在页面上的异常有的异常就是这个。如果你用Postman之类的处理测试出了异常则是站群服务器:
{ "timestamp": "2021-04-29T22:45:33.231+0000", "status": 500, "message": "Internal Server Error", "path": "foo/bar" }这个是怎么实现的呢?Spring Boot在启动时会注册一个ErrorPageFilter,当Servlet发生异常时,异常有的异常该过滤器就会拦截处理,处理将异常根据不同的异常有的异常策略进行处理:当异常已经在处理的话直接处理,否则转发给对应的错误页面。有兴趣的可以去看下源码,逻辑不复杂,这里就不贴了。
另外当一个 Servlet 抛出一个异常时,处理异常的Servlet可以从HttpServletRequest里面得到几个属性,如下:
异常属性
我们可以从上面的几个属性中获取异常的详细信息。
默认错误页面
通常Spring Boot出现异常默认会跳转到/error进行处理,而/error的云南idc服务商相关逻辑则是由BasicErrorController实现的。
@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); } // 返回json @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); } // 其它省略 }而对应的配置:
@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())); }所以我们只需要重新实现一个ErrorController并注入Spring IoC就可以替代默认的处理机制。而且我们可以很清晰的发现这个BasicErrorController不但是ErrorController的实现而且是一个控制器,如果我们让控制器的方法抛异常,肯定可以被自定义的统一异常处理。所以我对BasicErrorController进行了改造:
@Controller @RequestMapping("${ server.error.path:${ error.path:/error}}") public class ExceptionController extends AbstractErrorController { public ExceptionController(ErrorAttributes errorAttributes) { super(errorAttributes); } @Override @Deprecated public String getErrorPath() { return null; } @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { throw new RuntimeException(getErrorMessage(request)); } @RequestMapping public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { throw new RuntimeException(getErrorMessage(request)); } private String getErrorMessage(HttpServletRequest request) { Object code = request.getAttribute("javax.servlet.error.status_code"); Object exceptionType = request.getAttribute("javax.servlet.error.exception_type"); Object message = request.getAttribute("javax.servlet.error.message"); Object path = request.getAttribute("javax.servlet.error.request_uri"); Object exception = request.getAttribute("javax.servlet.error.exception"); return String.format("code: %s,exceptionType: %s,message: %s,path: %s,exception: %s", code, exceptionType, message, path, exception); } }直接抛异常,简单省力!凡是这里捕捉的到的异常大部分还没有经过Controller,我们通过ExceptionController中继也让这些异常被统一处理,保证整个应用的异常处理对外保持一个统一的门面。亿华云
很赞哦!(281)
上一篇:
相关文章
- 域名不仅仅是一个简单的网站。对于有长远眼光的公司来说,在运营网站之前确定一个优秀的域名对有长远眼光的公司来说是非常重要的。这对今后的市场营销、产品营销和企业品牌建设都具有十分重要的意义。优秀的域名是企业在市场竞争中获得持久优势的利器。
- 老生常谈的负载均衡,你真的懂了吗?
- 关于鉴权,看懂这篇就够了
- Nginx,永远滴神!
- 众所周知,com域名拥有最大的流通市场和流通历史。最好选择com域名,特别是在购买域名时处理域名。其次可以是cn域名、net域名、org域名等主流域名,现在比较流行的王域名和顶级域名,都是值得注册和投资的。
- 搞定Tomcat重要参数调优!
- Esp8266入门之一串口输出 Helloword 程序
- Linux下如何部署FTP服务器
- 在更换域名后,并不是就万事大吉了,我们需要将旧域名做301重定向到新域名上,转移旧域名的权重到新域名上。
- 出色完成首考,崇礼冬奥医疗救治保障构筑坚实信息保障平台
站长推荐
公司名字不但要与其经营理念、活动识别相统一,还要能反映公司理念,服务宗旨、商品形象,从而才能使人看到或听到公司的名称就能产生愉快的联想,对商店产生好感。这样有助于公司树立良好的形象。
Nodejs源码解析之UDP服务器
面试官:来说说Tomcat的启动过程是什么样子的
分布式Session的几种解决方案,你中意哪种?
只要我们做的是从目前的市场情况选择域名,从简单易记,从个性特征上,我们就可以找到一个好域名进行注册。域名注册进行域名记录和解析以及绑定网站后,客户可以通过URL登录您的网站。
Keepalived+Lvs+Nginx搭建Nginx高可用集群
Web服务器(Tomcat)高级优化
戴尔科技 AI涵盖多种技术,优化资源提升生产效率