Handling Global Exceptions

Use a @RestControllerAdvice class with an @ExceptionHandler to send every error back in one format, 404 for a path that doesn't exist and 500 for anything else.

Freelancer · Spring Boot · REST API · Updated

By

Some errors happen on the server before our controller can respond.

Spring MVC allows us to create a global error handler class that determines what information we want to send back to the client in these events.

Creating an Error Model

An error model allows you to control the message format and details that are sent to the client.

public class Error
{
    private int status;
    private String error;
    private String message;

    public Error(HttpStatus status)
    {
        this.status = status.value();
        this.error = status.getReasonPhrase();
    }

    // add getters and setters (setMessage is used below)
}

Creating the Global Exception Handler

Create a new GlobalExceptionHandler class as follows.

@RestControllerAdvice
public class GlobalExceptionHandler
{
    // This method gets called for any global exception
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Error> handleGlobalException(
                        Exception ex,
                        WebRequest request
    )
    {
        // check if this should be a 404 or 500 response
        if(ex instanceof ErrorResponse
        &&
        ((ErrorResponse)ex).getStatusCode() == HttpStatus.NOT_FOUND)
        {
            // all 404 errors
            Error body = new Error(HttpStatus.NOT_FOUND);
            body.setMessage("The requested resource was not found");

            return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
        }
        else
        {
            // all other errors
            Error body = new Error(HttpStatus.INTERNAL_SERVER_ERROR);
            body.setMessage("Something went wrong on the server. Please try again later.");

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

Do it: build the error body for each exception

The global handler's real decision is which error body each exception gets. Write that decision as a method of its own, and add one more case: a request whose body can't be read, such as JSON with a missing quote, should get 400 Bad Request instead of 500.

The box has no Spring, so the bottom of the file has small stand-ins. Leave them as they are:

  • HttpStatus: Spring's statuses, with value() (404) and getReasonPhrase() ("Not Found").
  • StatusException: an exception that carries a status, with getStatusCode(). It stands in for Spring's exceptions that are an ErrorResponse.
  • ApiError: the lesson's Error model, named ApiError here so it isn't mixed up with Java's own Error class. new ApiError(status) fills in status and error from the HttpStatus, and setMessage sets the message.

The method gets one value:

  • ex: the exception that reached the handler, an Exception.

Each exception gets one body:

The exception status error message
a StatusException whose status is NOT_FOUND 404 Not Found The requested resource was not found
a StatusException whose status is BAD_REQUEST 400 Bad Request The request could not be read
anything else 500 Internal Server Error Something went wrong on the server. Please try again later.

For example, a client sends GET /api/categoriez, a typo, and Spring throws a StatusException with HttpStatus.NOT_FOUND. So errorFor(ex) returns an ApiError whose status is 404, error Not Found and message The requested resource was not found.

Your job: change the method errorFor(Exception ex) so it returns the right ApiError for each row of the table.

  • A StatusException with NOT_FOUND gets the 404 body.
  • A StatusException with BAD_REQUEST gets the 400 body.
  • Anything else, including a StatusException with another status, gets the 500 body, as the starter already does.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets