Spring Boot错误控制器无法生效问题求助
嘿,我来帮你搞定这个错误处理控制器不生效的问题,咱们一步步排查:
1. 先检查错误控制器的注解和实现是否正确
首先得确保你的错误处理类配置对了——要么实现ErrorController接口,要么用@ControllerAdvice+@ExceptionHandler的组合,这俩是Spring Boot里最常用的自定义错误处理方式:
方式一:实现ErrorController(适合统一处理所有错误请求)
@Controller public class CustomErrorController implements ErrorController { @RequestMapping("/error") public String handleError(HttpServletRequest request) { // 可以根据状态码返回不同的错误页面 Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); if (status != null) { Integer statusCode = Integer.valueOf(status.toString()); if(statusCode == HttpStatus.NOT_FOUND.value()) { return "error/404"; // 对应templates/error/404.html } else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) { return "error/500"; } } return "error/generic"; } // 注意:Spring Boot 2.3及以上版本不需要重写getErrorPath(),默认就是"/error" }
方式二:用@ControllerAdvice全局捕获异常
这种方式更灵活,可以针对特定异常单独处理:
@ControllerAdvice public class GlobalExceptionHandler { // 捕获所有通用异常 @ExceptionHandler(Exception.class) public String handleGlobalException(Exception ex, Model model) { model.addAttribute("errorMsg", ex.getMessage()); return "error/generic"; } // 针对空指针异常单独处理 @ExceptionHandler(NullPointerException.class) public String handleNullPointer(NullPointerException ex, Model model) { model.addAttribute("errorMsg", "触发了空指针异常"); return "error/400"; } }
2. 确认白标错误页的禁用配置是否正确
你提到用@EnableAutoConfiguration(exclude),但要注意:@SpringBootApplication已经包含了@EnableAutoConfiguration,所以直接在这个注解里加排除就行,不用单独写@EnableAutoConfiguration,正确的写法是:
@SpringBootApplication(scanBasePackages="au.com.sample", exclude = ErrorMvcAutoConfiguration.class) public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
不过其实如果你的自定义错误控制器配置正确,Spring Boot会自动禁用白标页面,所以优先检查控制器本身的问题。
3. 检查Thymeleaf错误模板的路径
确保你的错误模板(比如404.html)放在src/main/resources/templates/error/目录下,Thymeleaf才能正确找到。如果路径错了,控制器返回了视图名但找不到模板,就会 fallback到默认的白标页面。
4. 排查是否有请求映射冲突
看看有没有其他控制器的@RequestMapping覆盖了/error路径,如果有的话,你的自定义错误控制器就会被拦截,无法生效。
5. 开debug日志找线索
如果上面都没问题,就开启debug日志看看Spring Boot有没有加载你的自定义控制器,以及错误处理的流程。在application.properties里添加:
logging.level.org.springframework.web=DEBUG logging.level.org.springframework.boot.autoconfigure=DEBUG
通过日志你能清楚看到Spring Boot是选择了你的自定义处理逻辑,还是用了默认的白标页面。
内容的提问来源于stack exchange,提问作者dave

