0

I would like to through an exception in spring boot that is descriptive and has a reason included ie. "Dog not found". At the moment I get the exception but it is generic:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Apr 20 09:32:07 CEST 2021
There was an unexpected error (type=Not Found, status=404).

The error is thrown from the @Service method implementation:

@Service
public class DogServiceImpl implements DogService {
    @Autowired
    DogRepository dogRepository;

    public String retrieveDogBreedById(Long id){

        Optional<String> optionalBreed = Optional.ofNullable(dogRepository.findBreedById(id));
        String breed = optionalBreed.orElseThrow(DogNotFoundException::new);
        return breed;

    };

And here is my exception:

@ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Dog not found")
public class DogNotFoundException extends RuntimeException{
    public DogNotFoundException() {
    }

    public DogNotFoundException(String message) {
        super(message);
    }
}

I am using @RestController for a REST API

Ana Sustic
  • 425
  • 2
  • 17

3 Answers3

2

The Error Handling Spring Boot Starter allows to very easily do this. See https://foojay.io/today/better-error-handling-for-your-spring-boot-rest-apis/ for a quick overview or https://wimdeblauwe.github.io/error-handling-spring-boot-starter/ for the full docs.

If you just throw DogNotFoundException when defined like this:

@ResponseStatus(value= HttpStatus.NOT_FOUND)
public class DogNotFoundException extends RuntimeException{
    public DogNotFoundException() {
      super("Dog not found");
    }

    public DogNotFoundException(String message) {
        super(message);
    }
}

, then the library will ensure the following response by default:

{
  "code":"DOG_NOT_FOUND",
  "message":"Dog not found"
}

(Disclaimer: I am the author of the library)

Wim Deblauwe
  • 25,113
  • 20
  • 133
  • 211
0

I solved it with using @ControllerAdvice which allows to handle exceptions across the whole application in one global handling component.

@ControllerAdvice
public class ControllerAdvisor extends ResponseEntityExceptionHandler {
    @ExceptionHandler(DogNotFoundException.class)
    public ResponseEntity<Object> handleDogNotFoundException(
            DogNotFoundException ex, WebRequest request) {

        Map<String, Object> body = new LinkedHashMap<>();

        body.put("message", "Dog not found");
        body.put("timestamp", LocalDateTime.now());

        return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
    }

}
Ana Sustic
  • 425
  • 2
  • 17
0

Check the spring boot version.

You need add server.error.include-message = always in the application.properties

See

Spring Boot RestController, On Error Status Response Body, Message of Error is empty

Harsh
  • 812
  • 1
  • 10
  • 23