Lesson 7 of 12 · 10 min · Building REST APIs

Exception handlers and standard error responses

Covers: Spring Boot 4.1 and Spring Framework 7 on Java 17 or newer. Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • Map exceptions to HTTP responses in one place with @RestControllerAdvice
  • Return errors in the standard ProblemDetail (RFC 9457) format
  • Turn validation failures into a clear list of field errors
  • Add a safe catch-all handler for unexpected errors
  • Test error responses

In simple words

Things go wrong: an order does not exist, a field is missing, the database is down. If every controller handles its own errors, each one reports them differently, and sooner or later one leaks a scary stack trace to the customer. A central exception handler is a single "complaints desk": every exception goes there, and the desk decides the right status code and a consistent, polite message.

Words to know

  • Exception handler: a method that turns a specific exception into an HTTP response.
  • Controller advice: a class whose handlers apply to all controllers.
  • Problem details: a standard JSON format for HTTP API errors (RFC 9457).
  • Catch-all: a last handler for any exception nobody else handled.

The default behaviour

Out of the box, Spring Boot maps an unhandled exception to a 500 response with a default JSON body (timestamp, status, error, path) from /error. It also maps some framework exceptions to proper codes (400 for an unreadable body, 405 for a wrong method, 415 for an unsupported media type). That is not good enough for an API: domain exceptions such as OrderNotFoundException should be 404, and the error format should be consistent. Also, never expose the stack trace or the exception message of unexpected errors: server.error.include-stacktrace and include-message default to safe values; leave them that way in production.

A central handler

@RestControllerAdvice
public class ApiExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);

    @ExceptionHandler(OrderNotFoundException.class)
    public ProblemDetail handleNotFound(OrderNotFoundException e) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        problem.setTitle("Order not found");
        problem.setProperty("orderId", e.orderId());
        return problem;
    }

    @ExceptionHandler(InsufficientStockException.class)
    public ProblemDetail handleConflict(InsufficientStockException e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
    }

    @ExceptionHandler(Exception.class)                       // last resort: do not leak internals
    public ProblemDetail handleUnexpected(Exception e) {
        log.error("Unhandled exception", e);                 // log the cause once, with the stack trace
        return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR,
                "An unexpected error occurred");
    }
}
  • @RestControllerAdvice = @ControllerAdvice + @ResponseBody: the handlers apply to all controllers (restrict with basePackages or assignableTypes).
  • @ExceptionHandler(X.class) handles X and its subclasses; the most specific handler wins.
  • Handler methods can take the exception, the request and the response as parameters, and return a ProblemDetail, a ResponseEntity or any body (with @ResponseStatus).
  • A handler inside a controller handles only that controller's exceptions.

ProblemDetail: the standard format

RFC 9457 (which replaced RFC 7807) defines "problem details for HTTP APIs", with the media type application/problem+json. Spring Framework supports it directly through the ProblemDetail class:

{
  "type": "about:blank",
  "title": "Order not found",
  "status": 404,
  "detail": "Order 5 was not found",
  "instance": "/orders/5",
  "orderId": 5
}

The standard fields are type (a URI identifying the kind of problem; about:blank means "just use the status"), title, status, detail and instance. You can add your own properties (orderId, errors), which Spring writes as extra JSON fields. Using one format everywhere means mobile and web clients write error handling once.

To get this format for Spring's own exceptions (404 for an unknown URL, 400 for a malformed body, 405, 415, validation errors), either set spring.mvc.problemdetails.enabled=true (check the application-properties appendix for your version) or extend ResponseEntityExceptionHandler in your advice class, which handles all standard Spring MVC exceptions and returns ProblemDetail:

@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
    // add your own @ExceptionHandler methods here
}

Handling validation errors

A failed @Valid @RequestBody raises MethodArgumentNotValidException. Override the handler in ResponseEntityExceptionHandler to list the field errors:

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {

    List<Map<String, String>> errors = ex.getBindingResult().getFieldErrors().stream()
            .map(f -> Map.of("field", f.getField(), "message", String.valueOf(f.getDefaultMessage())))
            .toList();

    ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
    problem.setTitle("Invalid request");
    problem.setProperty("errors", errors);
    return ResponseEntity.badRequest().body(problem);
}

The response:

{
  "title": "Invalid request",
  "status": 400,
  "detail": "Validation failed",
  "errors": [
    {"field": "email", "message": "must be a well-formed email address"},
    {"field": "age", "message": "must be greater than or equal to 18"}
  ]
}

For constraint violations on path and query parameters, handle ConstraintViolationException (and in recent Spring versions HandlerMethodValidationException) the same way and return 400. For a database unique constraint violation (DataIntegrityViolationException), return 409 Conflict with a message such as "email already registered", not the raw SQL error.

Which exception, which status

Exception Status
validation failure, malformed JSON, type mismatch 400
missing or invalid credentials (AuthenticationException) 401
not allowed (AccessDeniedException) 403
domain "not found" 404
duplicate or conflicting state, optimistic-lock failure 409
a dependency failed (payment gateway down) 502 or 503
anything unexpected 500

Security exceptions are thrown before reaching controllers (inside the security filter chain), so handle them in Spring Security's AuthenticationEntryPoint and AccessDeniedHandler (the security lesson), not in @ExceptionHandler.

Good error design

  • Stable codes: add a machine-readable code property ("ORDER_NOT_FOUND") so clients do not parse text.
  • Helpful, safe messages: say what the client can fix; never include SQL, class names, stack traces or secrets.
  • Correlation id: return a request id (traceId) so support can find the matching log lines; Micrometer Tracing adds one to logs automatically.
  • Log once, at the boundary: log 5xx errors with stack traces in the catch-all handler; log expected 4xx at INFO or DEBUG without the trace, to avoid noise.
  • Consistency: every endpoint, every error, the same shape.
  • Internationalisation: ProblemDetail titles and details can use MessageSource for translated text.

Testing

@WebMvcTest(OrderController.class)
class OrderControllerErrorTests {

    @Autowired MockMvcTester mvc;
    @MockitoBean OrderService service;

    @Test
    void unknownOrderReturnsProblemDetail() {
        given(service.get(5)).willThrow(new OrderNotFoundException(5));

        assertThat(mvc.get().uri("/orders/5"))
            .hasStatus(HttpStatus.NOT_FOUND)
            .bodyJson().extractingPath("$.title").isEqualTo("Order not found");
    }
}

(Boot 4 test classes: @WebMvcTest lives in org.springframework.boot.webmvc.test.autoconfigure, and @MockitoBean replaces @MockBean.) Test the error paths as seriously as the happy paths, including that an unexpected exception returns a 500 without internal details.

Common mistakes

  • Letting exceptions become default 500s for expected situations.
  • Returning stack traces or SQL to clients.
  • Catching Exception inside controllers instead of using one advice.
  • Different error shapes in different endpoints.
  • Logging every 4xx with a stack trace, or logging nothing for 5xx.
  • Trying to handle security exceptions with @ExceptionHandler.
  • Mapping unique-constraint failures to 500.

Try it yourself

  1. Create OrderNotFoundException and an advice that returns 404 as a ProblemDetail.
  2. Extend ResponseEntityExceptionHandler, send a malformed JSON body and a wrong HTTP method, and inspect the responses.
  3. Return a field-error list for validation failures.
  4. Add a catch-all that logs the exception and returns a generic 500, and write a test proving no message leaks.
  5. Add a code property to your errors and document the codes.

Check yourself

What does @RestControllerAdvice do?

It declares a class whose @ExceptionHandler methods apply to all controllers, with return values written to the response body.

What is ProblemDetail?

Spring's representation of the standard RFC 9457 error format with type, title, status, detail, instance and optional extra properties.

Why should the catch-all handler return a generic message?

Exception messages and stack traces can reveal internals (SQL, class names, paths) useful to attackers; log the real error on the server and return a safe message.

Which status code should a unique-constraint violation map to?

409 Conflict, with a message such as "email already registered".

Interview questions

How do you handle exceptions globally in Spring Boot?

Create a @RestControllerAdvice class with @ExceptionHandler methods for each exception type (optionally extending ResponseEntityExceptionHandler), returning ProblemDetail or ResponseEntity with the right status and a consistent body.

What happens when two @ExceptionHandler methods could match an exception?

The one for the most specific exception class is chosen; handlers local to a controller take precedence over advice handlers.

Where are authentication and authorisation errors handled?

In Spring Security's filter chain through AuthenticationEntryPoint (401) and AccessDeniedHandler (403), because they happen before the request reaches Spring MVC controllers.

Summary

  • One @RestControllerAdvice maps exceptions to status codes and a single error shape.
  • Use ProblemDetail (RFC 9457) and extend ResponseEntityExceptionHandler for Spring's own exceptions.
  • Return field-level validation errors, 409 for conflicts, and a safe catch-all 500 that logs the cause once.
  • Security exceptions are handled in the security filter chain; test the error paths.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.