资讯动态

c -> true 导致异常返回 404 问题排查

发布时间:2026/8/7 17:44:18 来源:尧图企业网站定制
最近在新开一个项目在新建基础架构的时候遇到了一个很有意思的问题接口正常访问时返回200Controller 中人为制造异常后后端日志明确打印了异常但前端Apifox收到的却是404理论上应该返回500最终排查发现根因是 Spring Boot 全局路径前缀配置污染了系统内置的/error路由。这个问题非常具有迷惑性记录一下完整排查过程。一、问题现象Controller层制造异常用于测试异常处理 int a 1 / 0;二、后端日志java.lang.ArithmeticException: / by zero完整调用链中可以看到Servlet.service() for servlet [dispatcherServlet] threw exception说明Controller 已经执行异常已经抛出Spring MVC 已经捕获异常按正常逻辑应该返回500 Internal Server Error但实际上Apifox 返回404 Not Found三、第一次怀疑方向一开始怀疑1. AOP 吞异常因为项目里有Around public Object around(ProceedingJoinPoint point)很多项目会写成try { return point.proceed(); } catch (Exception e) { } return null;这种会导致Spring 找不到返回视图最终变成 404但检查后发现AOP 没问题2. 全局异常处理器怀疑ControllerAdvice或者ExceptionHandler吞掉异常检查后排除四、真正的问题项目中有如下配置Configuration public class WebConfig implements WebMvcConfigurer { Override public void configurePathMatch(PathMatchConfigurer configurer) { // 为所有 Controller 添加 /api 前缀 configurer.addPathPrefix(/api, c - true); } }问题就出在c - true五、问题原理分析这段代码的意思是给所有 Controller 都加/api前缀。注意这里的“所有 Controller”不仅仅包括自己写的 Controller还包括Spring Boot 内置 ControllerBasicErrorController/erroractuatorswagger 等六、为什么正常接口还能返回 200正常情况下请求流程DispatcherServlet- Controller- return AjaxResult.success()- 200因为没有异常不会进入/error所以一切正常因此返回200 OK七、为什么异常时变成 404出现异常后Spring MVC 流程DispatcherServlet- Controller 抛异常- 异常解析器- 转发到 /error正常应该/error- BasicErrorController- 返回 500但由于addPathPrefix(/api, c - true)Spring 内置/error也被加了前缀/api/error现在问题就来了Spring Boot 默认真正注册的是/error不是/api/error于是异常发生后/api/error找不到。最终404 Not Found八、问题本质这里的 404并不是业务接口不存在而是异常处理路由不存在九、最终解决方案不要给所有 Controller 都加前缀。应该只给自己的业务 Controller 加。修改为Configurationpublic class WebConfig implements WebMvcConfigurer {Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.addPathPrefix(/api,c - c.getPackageName().startsWith(com.bs.web.controller));}}这样自己业务 Controller/api/xxxSpring 系统 Controller/error不会受影响总结c - true 这种全匹配不要随便使用Spring Boot 的/error一旦被污染各种诡异问题都会出现

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价