I am using Spring Boot 3 to develop a simple Rest API and want to handle exceptions using @RestControllerAdvice, but my code is throwing a 500 error even if the code in @exceptionHandler is throwing a 404 error code. I verified in debugging that execution reaches the ExceptionHandler method, but the default exception is still thrown.
Below is sample code for:
@RestControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public Messsage resourceNotFoundException(ResourceNotFoundException exception, WebRequest request) {
return new Messsage(HttpStatus.NOT_FOUND.value(), exception.getMessage(), LocalDateTime.now());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(code = HttpStatus.NOT_FOUND)
public Messsage globalException(Exception exception, WebRequest request) {
return new Messsage(HttpStatus.NOT_FOUND.value(), exception.getMessage(), LocalDateTime.now());
}
}