0

I'm developing Rest API with Spring Boot 2 and I'm trying to create an ExceptionHandler but it seems it doesn't working.

I have the following @GetMapping method:

@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();
}

The customerRepository it's an interface that extends CrudRepository interface.

The @ExceptionHandler for customerNotFoundException it's the following:

@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);
}

I also have annotated the ResponseEntityExceptionHandler extended class as following:

@Slf4j
@RestController
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

The problem is that when I call a request for a customerId that it's not exists in the database, I don't receive only the CustomerNotFoundException message, but a very long stacktrace like:

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

and so on...

what is the problem?

Thank you!

Dina Bogdan
  • 4,345
  • 5
  • 27
  • 56

1 Answers1

0

Thanks to @bestwishes, I've found the solution. This was returning

new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND)

instead returning

new ResponseEntity(customerNotFoundException, HttpStatus.NOT_FOUND)

in handleCustomerNotFoundException method from CustomResponseEntityExceptionHandler class.

Dina Bogdan
  • 4,345
  • 5
  • 27
  • 56