当前位置: 首页 > 知识库问答 >
问题:

异常处理程序在spring boot中不起作用

盖诚
2023-03-14

我正在用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消息,而是一个非常长的stacktrace:

{"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},

等等...

问题出在哪里?

谢谢!

共有1个答案

施冠玉
2023-03-14

感谢@bestwishes,我找到了解决办法。这是回来的

new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND)

而是返回

new ResponseEntity(customerNotFoundException, HttpStatus.NOT_FOUND)

在CustomResponseEntityExceptionHandler类的handleCustomerNotFoundException方法中。

 类似资料: