Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 66 ยท Building REST APIs

Error Handling and Problem Details

Return consistent errors from a Spring Boot API: @RestControllerAdvice, @ExceptionHandler, ProblemDetail (RFC 9457) and no leaked stack traces.

Every API fails sometimes: the book does not exist, the JSON is broken, the database is down. What matters is how it fails. A good API answers with the right status code and a small, predictable body that a client can parse. A bad one returns an HTML error page, a 500 with a Java stack trace, or a different shape for every endpoint.

Spring Boot gives you tools to centralize all of that in one place instead of scattering try/catch blocks through your controllers. This lesson covers @ExceptionHandler, @RestControllerAdvice, the standard ProblemDetail format (RFC 9457), ResponseStatusException, and the rule that decides what the client may see. It follows Bean Validation, whose exceptions you will map here, and the Java-level background is in Validation and Error Handling.

Real Spring code is read-only on this site. The TryIts build a small handler dispatcher that behaves the way Spring's exception resolution does, so you can see the matching rules run.

Let exceptions travel

The cleanest controller does not catch exceptions. It throws a meaningful exception from the service layer, or lets a library throw one, and the framework turns it into a response:

Java
@GetMapping("/{id}")
BookResponse find(@PathVariable long id) {
    return bookService.find(id);   // throws BookNotFoundException if missing
}
Java
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) {
        super("No book with id " + id);
    }
}

When a controller method throws, Spring MVC asks a chain of exception resolvers whether any of them can handle it. If none can, the exception goes to the servlet container, which answers 500, and Boot's default error page or JSON takes over. Your job is to add resolvers that know your exceptions.

Who handles an exception

Local handler An @ExceptionHandler in the same controller.
Advice A @RestControllerAdvice shared by all controllers.
Status annotation @ResponseStatus or ResponseStatusException.
Boot fallback The /error page, always last.

The first handler that matches wins.

1 / 2

@ExceptionHandler and @RestControllerAdvice

An @ExceptionHandler method says "I turn this exception into a response". Placed in a controller, it only covers that controller. Placed in a class annotated @RestControllerAdvice, it covers every controller:

Java
@RestControllerAdvice
class ApiExceptionHandler {

    @ExceptionHandler(BookNotFoundException.class)
    ResponseEntity<ProblemDetail> notFound(BookNotFoundException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.NOT_FOUND, ex.getMessage());
        problem.setTitle("Book not found");
        return ResponseEntity.status(404).body(problem);
    }

    @ExceptionHandler(Exception.class)
    ProblemDetail unexpected(Exception ex) {
        log.error("Unhandled exception", ex);
        return ProblemDetail.forStatusAndDetail(
            HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong.");
    }
}

When several handlers could match, Spring picks the one whose declared exception type is closest to the thrown type in the class hierarchy. A BookNotFoundException goes to its own handler; an IllegalStateException falls through to the Exception handler. The next TryIt implements that rule so you can watch it work.

Java A mini exception-advice dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

BookMissing has an exact handler, NotFound has its own, and the IllegalStateException falls back to the general Exception handler. In real Spring the lookup is similar: the closest match wins, and two methods in one class that handle the same exception type are rejected as ambiguous.

ProblemDetail and RFC 9457

Inventing your own error JSON for every API means every client needs custom code. RFC 9457 "Problem Details for HTTP APIs" (the successor of RFC 7807) defines one small standard shape, served as application/problem+json:

JSON
{
  "type": "https://api.example.com/problems/book-not-found",
  "title": "Book not found",
  "status": 404,
  "detail": "No book with id 7",
  "instance": "/books/7"
}
  • type is a URI that identifies the kind of problem (use about:blank when the status says it all).
  • title is a short, stable summary for that kind of problem.
  • status repeats the HTTP status code.
  • detail explains this particular occurrence.
  • instance identifies this occurrence, usually the request path.
  • Any other fields are allowed as extensions, such as a list of validation errors.

Spring has this built in as the ProblemDetail class. Return it from a handler and Spring writes it with the right content type. To get problem responses for the framework's own exceptions (404 for no handler, 405, 415, malformed JSON) switch it on with one property:

YAML
spring:
  mvc:
    problemdetails:
      enabled: true

Alternatively, extend ResponseEntityExceptionHandler in your advice class. It already knows how to convert Spring MVC's standard exceptions to problem details, and you override only the methods you want to change. Adding custom fields uses setProperty:

Java
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalid(MethodArgumentNotValidException ex) {
    ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
    problem.setTitle("Validation failed");
    problem.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
        .map(e -> Map.of("field", e.getField(), "message", String.valueOf(e.getDefaultMessage())))
        .toList());
    return problem;
}

Clients then see every field problem at once, in the same envelope as every other error.

ResponseStatusException for quick cases

For a one-off error that does not deserve its own exception class, throw ResponseStatusException:

Java
Book book = repository.findById(id)
    .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No book " + id));

It carries a status and a reason, and Spring turns it into a response (a problem detail when problem details are on). It is handy in small apps and prototypes. In larger code bases, domain exceptions such as BookNotFoundException read better, keep HTTP out of your service layer, and are easier to unit test. The older @ResponseStatus(HttpStatus.NOT_FOUND) annotation on an exception class is a middle path with less flexibility: the body cannot be customized.

Never leak internals

The most important rule of error handling is about what you leave out. A stack trace, a SQL error text, a file path or a class name tells an attacker which framework, which tables and which versions you run, and tells a normal user nothing useful. The rule:

  • Client errors (4xx): say what is wrong with the request. The details are safe because the client sent the data.
  • Server errors (5xx): log everything on the server, return a short generic message, and include a correlation id so support can find the log entry.

Boot's own defaults help: server.error.include-stacktrace is never, and include-message and include-binding-errors are also off by default in recent versions. Do not turn them on in production. The TryIt below shows both sides: a mapping function that exposes the message for expected failures and hides the cause for unexpected ones, with a correlation id that ties the response to the server log.

Java Safe error bodies with a correlation id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The client of the second request learns nothing about the database host, but a developer can search the log for err-1000.

Status codes that fit

Choose the status that matches the cause, because clients and proxies act on it:

  • 400 malformed or invalid input; 422 is also used for syntactically valid but semantically wrong data.
  • 401 not authenticated; 403 authenticated but not allowed.
  • 404 the resource does not exist (also a safe answer when you do not want to reveal that it exists).
  • 409 a conflict with the current state, such as a duplicate or an outdated version.
  • 500 your bug; 503 temporarily unavailable.

Write one test per mapped exception that calls the handler (or the endpoint, with the MockMvc tools you will meet in Testing Controllers with MockMvc) and checks status, content type and body. Error responses are part of your API contract.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the advantage of a @RestControllerAdvice class over try/catch in each controller?

    One advice class centralizes the mapping from exceptions to responses, so every endpoint fails the same way and controllers stay free of error plumbing.
  2. 2. Two handlers exist, one for Exception and one for IllegalArgumentException. Which runs for an IllegalArgumentException?

    Spring picks the handler whose declared exception type is nearest in the class hierarchy to the thrown exception.
  3. 3. Which media type does an RFC 9457 problem detail use?

    Problem details are served as application/problem+json (or application/problem+xml), so clients can recognize the standard error shape.
  4. 4. What should a 500 response body contain?

    Internals help attackers and confuse users. Log the details server-side and give the client an id that links the response to the log entry.
  5. 5. Which property enables problem details for Spring MVC's own exceptions such as 405 and 415?

    The spring.mvc.problemdetails.enabled property makes the framework's built-in exceptions render as ProblemDetail. Extending ResponseEntityExceptionHandler gives the same effect with more control.

Summary

  • Let exceptions travel up; handle them centrally with @RestControllerAdvice and @ExceptionHandler.
  • The handler with the closest exception type wins; keep a general Exception handler as a safety net.
  • Use ProblemDetail (RFC 9457) for a standard application/problem+json body; add extension fields with setProperty.
  • ResponseStatusException is a quick tool; domain exceptions keep HTTP out of services.
  • Never leak stack traces, SQL or paths: expose 4xx details, log 5xx details and return a correlation id.
  • Pick status codes by cause: 400, 401, 403, 404, 409, 500.

Next: Designing a Clean API.