Spring Boot 2中Exception Handler失效问题求助
嗨,我来帮你搞定这个异常处理器不生效的问题,先给你梳理几个最容易踩的坑,一个个排查应该就能解决:
1. 确保异常处理器类加对了注解
你得给你的异常处理类加上@RestControllerAdvice(Rest API场景首选,自带@ResponseBody,能直接返回JSON格式错误响应),或者@ControllerAdvice(MVC页面场景适用)。要是没加这个注解,Spring根本识别不到这是个全局异常处理器。
示例代码参考:
@RestControllerAdvice public class GlobalExceptionHandler { // 专门处理你的CustomerNotFoundException @ExceptionHandler(CustomerNotFoundException.class) public ResponseEntity<Map<String, Object>> handleCustomerNotFound(CustomerNotFoundException ex) { Map<String, Object> errorResponse = new HashMap<>(); errorResponse.put("status", HttpStatus.NOT_FOUND.value()); errorResponse.put("message", ex.getMessage()); return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND); } }
2. 自定义异常要继承RuntimeException
Spring默认只会自动捕获未检查异常(也就是RuntimeException及其子类)。如果你的CustomerNotFoundException是继承自Exception(受检异常),那要么把它改成继承RuntimeException,要么在@ExceptionHandler里明确声明处理这个受检异常。
正确的自定义异常写法:
public class CustomerNotFoundException extends RuntimeException { public CustomerNotFoundException(String message) { super(message); } }
3. 检查包扫描范围
你的异常处理器类要被Spring的组件扫描到才行!如果主启动类(带@SpringBootApplication的类)在根包(比如com.yourcompany.app),那异常处理器最好放在这个包或者它的子包下。要是不在的话,就得在@SpringBootApplication里指定扫描范围:
@SpringBootApplication(scanBasePackages = {"com.yourcompany.controller", "com.yourcompany.exception"}) public class YourSpringBootApplication { public static void main(String[] args) { SpringApplication.run(YourSpringBootApplication.class, args); } }
4. 别在控制器里吞掉异常
看看你的getCustomerById方法里有没有用try-catch把CustomerNotFoundException捕获了但没抛出去?要是你自己把异常吞了,全局异常处理器肯定收不到。确保你是直接抛出异常,补全后的代码应该是这样:
@GetMapping("/customers/{customerId}") public Customer getCustomerById(@PathVariable Long customerId) { log.debug("### Enter: getCustomerById() for id: " + customerId); Optional<Customer> customer = customerRepository.findById(customerId); if (!customer.isPresent()) { throw new CustomerNotFoundException("The customer with id: " + customerId + " was not found"); } return customer.get(); }
先排查这几个点,大部分情况下都是这几个原因导致的异常处理器不生效。如果还是不行,可以再看看控制台有没有报错信息,或者检查有没有其他优先级更高的异常处理器冲突。
内容的提问来源于stack exchange,提问作者Dina Bogdan

