Spring Boot中@ExceptionHandler未生效问题排查与解决
问题:自定义全局异常处理器未生效,返回默认错误响应
问题场景
学习RESTful Web服务开发时,实现了全局异常处理类,但测试时完全未生效:
- 编写了继承
ResponseEntityExceptionHandler的AppExceptionsHandler类,用@ControllerAdvice标注,意图捕获所有Exception类型异常并返回自定义错误结构 - 在
UserController的getUser方法中手动触发NullPointerException进行测试 - 实际运行时,控制台打印NPE堆栈信息,Postman返回Spring默认的500错误响应,异常处理器内的断点从未触发,即使将
@ExceptionHandler的参数改为NullPointerException.class也无效果
相关代码
全局异常处理器实现
@ControllerAdvice public class AppExceptionsHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = {Exception.class}) public ResponseEntity<CustomErrorMessage> handleAnyException(Exception ex, WebRequest request) { String customErrorMessageDescription = ex.getLocalizedMessage(); if (customErrorMessageDescription == null) customErrorMessageDescription = ex.toString(); CustomErrorMessage customErrorMessage = new CustomErrorMessage(new Date(), customErrorMessageDescription); return new ResponseEntity<>(customErrorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR); } }
测试用Controller方法
@GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) public ResponseEntity<UserRest> getUser(@PathVariable String userId) { String firstName = null; int length = firstName.length(); if (users.containsKey(userId)) { return new ResponseEntity<>(users.get(userId), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } }
实际返回的默认错误结构
{ "timestamp": 1699010452939, "status": 500, "error": "Internal Server Error", "path": "/users/bb3bd1f5-ab81-40f0-a025-d009e8e30ada" }
解决方案
排查后发现核心问题:全局异常处理类所在的包未被Spring容器扫描到。在Spring Boot应用的主启动类上添加@ComponentScan("你的异常处理器所在包名"),指定扫描包含该异常处理器的包路径后,异常处理器正常生效,能够返回自定义的错误响应结构。
内容的提问来源于stack exchange,提问作者Ioannis Zisis
相关产品推荐
相关产品推荐

