异常处理程序在Spring Boot

时间:2018-03-17 15:50:40

标签: spring-boot spring-data-jpa exceptionhandler

我正在使用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},

依旧......

问题是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

感谢@bestwishes,我找到了解决方案。这回来了

new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND)

而是返回

new ResponseEntity(customerNotFoundException, HttpStatus.NOT_FOUND)
来自CustomResponseEntityExceptionHandler类的handleCustomerNotFoundException方法中的