我正在使用 Spring Boot 2 开发 Rest API,我正在尝试创建一个 ExceptionHandler 但它似乎不起作用。
我有以下@GetMapping 方法:
@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();
}
customerRepository 它是一个扩展 CrudRepository 接口的接口。
customerNotFoundException 的 @ExceptionHandler 如下:
@ExceptionHandler(CustomerNotFoundException.class)
public final ResponseEntity handleCustomerNotFoundException
(CustomerNotFoundException customerNotFoundException, WebRequest webRequest) {
log.error("### Oups! We have a CustomerNotFoundException!!!");
ExceptionResponse exceptionResponse = new ExceptionResponse(
new Date(),
customerNotFoundException.getMessage(),
webRequest.getDescription(false));
return new ResponseEntity(customerNotFoundException, HttpStatus.NOT_FOUND);
}
我还将 ResponseEntityExceptionHandler 扩展类注释如下:
@Slf4j
@RestController
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
问题是,当我调用数据库中不存在的 customerId 的请求时,我不仅收到 CustomerNotFoundException 消息,而且收到很长的堆栈跟踪,例如:
{"cause":null,"stackTrace":[{"methodName":"getCustomerById","fileName":"CustomerResource.java","lineNumber":37,"className":"org.pdm.ib.pmt.router.controls.CustomerResource","nativeMethod":false},{"methodName":"invoke0","fileName":"NativeMethodAccessorImpl.java","lineNumber":-2,"className":"sun.reflect.NativeMethodAccessorImpl","nativeMethod":true},{"methodName":"invoke","fileName":"NativeMethodAccessorImpl.java","lineNumber":62,"className":"sun.reflect.NativeMethodAccessorImpl","nativeMethod":false},{"methodName":"invoke","fileName":"DelegatingMethodAccessorImpl.java","lineNumber":43,"className":"sun.reflect.DelegatingMethodAccessorImpl","nativeMethod":false},{"methodName":"invoke","fileName":"Method.java","lineNumber":498,"className":"java.lang.reflect.Method","nativeMethod":false},
等等...
问题是什么?
谢谢!