What You'll Learn

As previously stated, REST is a convention for APIs over HTTP. There are expectations that the HTTP verbs (GET, POST, PUT, etc) and HTTP status code will be used. When things go wrong, we want to catch those errors and return suitable errors so that the client can take action.

We can work in a Java-specific way, yet get the HTTP effect by creating an exception.

Create CharityNotFoundAPIException.java.

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Charity does not exist.")
public class CharityNotFoundAPIException extends RuntimeException {
    public CharityNotFoundAPIException(String s) {
        super(s);
    }
}

The @ResponseStatusis set to NOT_FOUND (which is a 404).

We'll add some checks to the API that returns a single charity. It is clearly possible to get a 404 here - just supply an non-existent acronym.

In CharitySearchAPIController

@GetMapping("/charity/{furl}")
public ResponseEntity<?> findByFurl(@PathVariable(value = "furl", required = true) String acronym) {
    Optional<CharityDTO> charityDTO;
    charityDTO = charitySearch.findByAcronym(acronym);

    if (charityDTO.isPresent()) {
        return ResponseEntity.ok(charityDTO.get());
    } else {
        throw new CharityNotFoundAPIException("That charity does not exist.");
    }
}

Again, we reuse the charity service and if a DTO is not present in the returned Optional, we throw an instance of our new exception.

Go to a browser and browse to localhost:8080/api/charity/nspcc.

This should return a 200 and the single JSON object.

Now try a missing acronym and check that a 404 is returned.

In this tutorial, we have created an API that will return a 404 if a resource is missing. There are other ways in Spring Boot of handling exceptions. We will examine them later.