Spring Boot exception handling: from thrown exception to error response

Every exception a controller throws becomes an HTTP response, but which status and body the client gets depends on which part of Spring handled it. This page explains the resolver chain and the /error fallback, then runs advice classes, ProblemDetail responses, validation errors and the two traps that turn client errors into 500s.

Contents

How Spring turns an exception into a response

When a controller method throws, the client still has to receive an HTTP response: a status code, some headers and usually a body that says what went wrong. Exception handling in Spring Boot is about deciding that response in one place, instead of wrapping every controller method in try and catch.

The exception passes through two layers, and knowing which one handled it explains most surprises:

  1. Spring MVC's exception resolvers: the DispatcherServlet catches the exception and offers it to a chain of HandlerExceptionResolver beans, in order. The first one that returns a result decides the response.
  2. The servlet container's error page: if no resolver handles the exception, or a resolver only calls response.sendError(status), Tomcat forwards the request to the error path. Spring Boot maps /error to its BasicErrorController, which writes the JSON body with timestamp, status, error and path.
The exception resolvers, in the order Spring MVC tries them
ResolverHandlesResponse
ExceptionHandlerExceptionResolverExceptions with a matching @ExceptionHandler method, in the controller or a @ControllerAdviceWhatever the handler returns
ResponseStatusExceptionResolverResponseStatusException and exceptions annotated with @ResponseStatussendError with that status, so the body comes from /error
DefaultHandlerExceptionResolverSpring MVC's own exceptions: missing parameter, wrong method, unsupported media type, no handlersendError with 400, 405, 415, 404 and so on
None of themEverything else, such as IllegalStateException500, with the body from /error

Since Spring Framework 6.0, Spring also supports RFC 9457 "problem details", a standard JSON error format with the content type application/problem+json and the fields type, title, status, detail and instance. The class ProblemDetail represents it, and the ErrorResponse interface lets an exception carry one. RFC 9457 replaced RFC 7807 in 2023 and keeps the same format.

All programs on this page use Spring Boot 4.1 with Spring Framework 7.0 and spring-boot-starter-webmvc; the validation example adds spring-boot-starter-validation. Several programs set logging.level.root=OFF, because a 500 makes Tomcat log a full stack trace, which is useful in a real application but would bury the output here.

What the client gets with no handlers

Before writing any handler, it helps to see what Spring Boot sends on its own. The controller throws one unexpected exception and one ResponseStatusException; the program also calls a wrong method and a path that does not exist. It runs the same application twice, the second time with problem details switched on:

Java
package demo.defaults;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@SpringBootApplication
public class DefaultErrors {

    @RestController
    static class OrderController {
        @GetMapping("/orders/{id}")
        public String order(@PathVariable int id) {
            if (id == 0) {
                throw new IllegalStateException("database is down");
            }
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no order " + id);
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static void call(String base, String method, String path) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(base + path))
                .method(method, BodyPublishers.noBody()).build();
        HttpResponse<String> r = HTTP.send(request, BodyHandlers.ofString());
        String body = r.body().replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"...\"");
        System.out.println(method + " " + path + " -> " + r.statusCode() + " "
                + r.headers().firstValue("Content-Type").orElse("-"));
        System.out.println("  " + body);
    }

    static void run(String title, String... extra) throws Exception {
        System.out.println("=== " + title);
        try (ConfigurableApplicationContext context =
                     new SpringApplicationBuilder(DefaultErrors.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .properties(extra)
                .run()) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String base = "http://localhost:" + port;
            call(base, "GET", "/orders/0");
            call(base, "GET", "/orders/7");
            call(base, "DELETE", "/orders/7");
            call(base, "GET", "/nothing-here");
        }
    }

    public static void main(String[] args) throws Exception {
        run("Spring Boot defaults");
        run("spring.mvc.problemdetails.enabled=true",
            "spring.mvc.problemdetails.enabled=true");
    }
}
Output
=== Spring Boot defaults
GET /orders/0 -> 500 application/json
  {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/orders/0"}
GET /orders/7 -> 404 application/json
  {"timestamp":"...","status":404,"error":"Not Found","path":"/orders/7"}
DELETE /orders/7 -> 405 application/json
  {"timestamp":"...","status":405,"error":"Method Not Allowed","path":"/orders/7"}
GET /nothing-here -> 404 application/json
  {"timestamp":"...","status":404,"error":"Not Found","path":"/nothing-here"}
=== spring.mvc.problemdetails.enabled=true
GET /orders/0 -> 500 application/json
  {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/orders/0"}
GET /orders/7 -> 404 application/problem+json
  {"detail":"no order 7","instance":"/orders/7","status":404,"title":"Not Found"}
DELETE /orders/7 -> 405 application/problem+json
  {"detail":"Method 'DELETE' is not supported.","instance":"/orders/7","status":405,"title":"Method Not Allowed"}
GET /nothing-here -> 404 application/problem+json
  {"detail":"No static resource nothing-here.","instance":"/nothing-here","status":404,"title":"Not Found"}

The program replaces each timestamp with ..., because it changes on every request.

  • With the defaults, all four responses have the same shape, produced by BasicErrorController after a sendError. Even the message of ResponseStatusException(NOT_FOUND, "no order 7") is missing: Spring Boot leaves out exception messages by default, so that internal details such as SQL errors do not leak to clients.
  • With spring.mvc.problemdetails.enabled=true, the 404 and 405 became application/problem+json with a useful detail, such as no order 7. Spring Boot registered a ResponseEntityExceptionHandler, which answers Spring MVC's own exceptions and ErrorResponse exceptions directly, without going through /error.
  • The IllegalStateException still produced the old shape in both runs. Problem details only apply to exceptions Spring knows; everything else still ends at /error, and needs a handler of your own if clients should see one format.

Running the first configuration with spring.web.error.include-message=always added "message":"database is down" and "message":"no order 7" to the default bodies. Spring Boot 4.0 moved these settings from server.error.* to spring.web.error.*, and the old names no longer have an effect. Show messages only in development: an exception message is written for developers, not for API clients.

@ExceptionHandler and @RestControllerAdvice

An @ExceptionHandler method turns an exception into a response. Inside a controller it applies to that controller only; inside a @RestControllerAdvice class it applies to every controller. This program has a small exception hierarchy and handlers at both levels, to show which one Spring chooses:

Java
package demo.advice;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@SpringBootApplication
public class AdviceHandlers {

    static class NotFoundException extends RuntimeException {
        NotFoundException(String message) {
            super(message);
        }
    }

    static class OrderNotFoundException extends NotFoundException {
        final long orderId;

        OrderNotFoundException(long orderId) {
            super("Order " + orderId + " does not exist");
            this.orderId = orderId;
        }
    }

    @RestController
    static class OrderController {
        @GetMapping("/orders/{id}")
        public String order(@PathVariable long id) {
            throw new OrderNotFoundException(id);
        }

        @GetMapping("/orders/{id}/invoice")
        public String invoice(@PathVariable long id) {
            throw new UnsupportedOperationException("invoices are not ready");
        }

        // Applies only to exceptions thrown by this controller, and wins over the advice
        @ExceptionHandler
        public ResponseEntity<String> notReady(UnsupportedOperationException e) {
            return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).body(e.getMessage());
        }
    }

    @RestController
    static class CustomerController {
        @GetMapping("/customers/{name}")
        public String customer(@PathVariable String name) {
            throw new NotFoundException("Customer " + name + " does not exist");
        }

        @GetMapping("/customers/{name}/invoice")
        public String invoice(@PathVariable String name) {
            throw new UnsupportedOperationException("invoices are not ready");
        }
    }

    @RestControllerAdvice
    static class ApiErrors {

        @ExceptionHandler
        public ProblemDetail orderMissing(OrderNotFoundException e) {
            ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                    HttpStatus.NOT_FOUND, e.getMessage());
            problem.setTitle("Order not found");
            problem.setType(URI.create("https://example.com/problems/order-not-found"));
            problem.setProperty("orderId", e.orderId);
            return problem;
        }

        @ExceptionHandler
        public ProblemDetail missing(NotFoundException e) {
            return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        }

        @ExceptionHandler
        public ProblemDetail unexpected(RuntimeException e) {
            return ProblemDetail.forStatusAndDetail(
                    HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static void get(String path) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(base + path)).build();
        HttpResponse<String> r = HTTP.send(request, BodyHandlers.ofString());
        System.out.println("GET " + path + " -> " + r.statusCode() + " "
                + r.headers().firstValue("Content-Type").orElse("-"));
        System.out.println("  " + r.body());
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(AdviceHandlers.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            get("/orders/42");
            get("/customers/zoe");
            get("/orders/42/invoice");
            get("/customers/zoe/invoice");
        }
    }
}
Output
GET /orders/42 -> 404 application/problem+json
  {"detail":"Order 42 does not exist","instance":"/orders/42","status":404,"title":"Order not found","type":"https://example.com/problems/order-not-found","orderId":42}
GET /customers/zoe -> 404 application/problem+json
  {"detail":"Customer zoe does not exist","instance":"/customers/zoe","status":404,"title":"Not Found"}
GET /orders/42/invoice -> 501 text/plain;charset=UTF-8
  invoices are not ready
GET /customers/zoe/invoice -> 500 application/problem+json
  {"detail":"Something went wrong","instance":"/customers/zoe/invoice","status":500,"title":"Internal Server Error"}
  • OrderNotFoundException matched three handlers in the advice: its own type, its parent NotFoundException, and RuntimeException. Spring chose the closest type in the class hierarchy, so the response carries the custom title, type and the extra orderId property.
  • The customer's plain NotFoundException went to the missing handler. Its title is the default for 404, Not Found.
  • Both invoice methods threw the same UnsupportedOperationException, but the results differ. In OrderController, the controller's own handler won over the advice and returned 501 as plain text. In CustomerController, which has no handler, the advice's RuntimeException handler returned 500.
  • Spring filled in instance with the request path in every ProblemDetail, and set the content type to application/problem+json, even though no handler set either.

The handlers take the exception type from their parameter, so @ExceptionHandler needs no value. A handler can also take the request, the HandlerMethod that failed, or a Locale, and can return a ProblemDetail, a ResponseEntity or any body. When there are several advice classes, @Order decides which one is asked first, and attributes such as @RestControllerAdvice(basePackages = "com.example.api") limit an advice to some controllers.

Exceptions that carry their own status

Instead of writing a handler for every exception, an exception can say which response it stands for. A seat booking has three kinds of failure, each declared a different way, and the program runs with problem details switched on:

Java
package demo.own;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@SpringBootApplication
public class OwnExceptions {

    // 1. Status fixed on the class
    @ResponseStatus(code = HttpStatus.CONFLICT, reason = "Seat already taken")
    static class SeatTakenException extends RuntimeException {}

    // 3. Carries a full ProblemDetail of its own
    static class InsufficientFundsException extends ErrorResponseException {
        InsufficientFundsException(long balance, long price) {
            super(HttpStatus.UNPROCESSABLE_CONTENT, asProblem(balance, price), null);
        }

        private static ProblemDetail asProblem(long balance, long price) {
            ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                    HttpStatus.UNPROCESSABLE_CONTENT,
                    "Balance " + balance + " is less than price " + price);
            problem.setTitle("Insufficient funds");
            problem.setProperty("balance", balance);
            problem.setProperty("price", price);
            return problem;
        }
    }

    @RestController
    static class BookingController {
        @GetMapping("/book/{seat}")
        public String book(@PathVariable String seat) {
            return switch (seat) {
                case "1A" -> throw new SeatTakenException();
                // 2. Status chosen where it is thrown
                case "99Z" -> throw new ResponseStatusException(
                        HttpStatus.BAD_REQUEST, "No seat 99Z on this aircraft");
                case "2B" -> throw new InsufficientFundsException(30, 120);
                default -> "booked " + seat;
            };
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static void get(String path) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(base + path)).build();
        HttpResponse<String> r = HTTP.send(request, BodyHandlers.ofString());
        System.out.println("GET " + path + " -> " + r.statusCode());
        String body = r.body().replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"...\"");
        System.out.println("  " + body);
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(OwnExceptions.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN",
                            "spring.mvc.problemdetails.enabled=true")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            get("/book/3C");
            get("/book/1A");
            get("/book/99Z");
            get("/book/2B");
        }
    }
}
Output
GET /book/3C -> 200
  booked 3C
GET /book/1A -> 409
  {"timestamp":"...","status":409,"error":"Conflict","path":"/book/1A"}
GET /book/99Z -> 400
  {"detail":"No seat 99Z on this aircraft","instance":"/book/99Z","status":400,"title":"Bad Request"}
GET /book/2B -> 422
  {"detail":"Balance 30 is less than price 120","instance":"/book/2B","status":422,"title":"Insufficient funds","balance":30,"price":120}
  • @ResponseStatus(code = CONFLICT, reason = "Seat already taken") gave 409, but in the old /error format, without the reason. The annotation makes ResponseStatusExceptionResolver call sendError, so problem details do not apply to it. This makes the annotation the weakest of the three choices.
  • ResponseStatusException gave 400 with its message as detail. It implements ErrorResponse, so the problem details handler answered it directly.
  • InsufficientFundsException extends ErrorResponseException and builds its whole ProblemDetail, with a title and two extra properties. The client got status 422 and the properties balance and price it can act on.

HttpStatus.UNPROCESSABLE_CONTENT is the Spring Framework 7 name for 422, following RFC 9110; the older constant UNPROCESSABLE_ENTITY is deprecated. Extending ErrorResponseException suits domain errors that always map to one response. When the same exception means different things in different APIs, keep it free of HTTP and map it in an advice instead.

Validation errors

Validation failures are the errors clients see most, and the default body tells them only that the request was invalid. A sign-up form with three rules, sent with all three broken, shows how to return every field error at once. The second endpoint validates a query parameter, which fails with a different exception:

Java
package demo.validation;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@SpringBootApplication
public class ValidationErrors {

    public record SignUp(@NotBlank String name, @Email String email,
                         @Min(18) int age) {}

    public record FieldProblem(String field, String message) {}

    @RestController
    static class SignUpController {
        @PostMapping("/signups")
        public String signUp(@Valid @RequestBody SignUp form) {
            return "welcome " + form.name();
        }

        @GetMapping("/signups")
        public String page(@RequestParam @Min(1) @Max(50) int size) {
            return "page of " + size;
        }
    }

    @RestControllerAdvice
    static class ApiErrors extends ResponseEntityExceptionHandler {

        @Override
        protected ResponseEntity<Object> handleMethodArgumentNotValid(
                MethodArgumentNotValidException ex, HttpHeaders headers,
                HttpStatusCode status, WebRequest request) {
            ProblemDetail problem = ex.getBody();          // already 400 with a detail
            List<FieldProblem> errors = ex.getBindingResult().getFieldErrors().stream()
                    .map(e -> new FieldProblem(e.getField(), e.getDefaultMessage()))
                    .sorted((a, b) -> a.field().compareTo(b.field()))
                    .toList();
            problem.setProperty("errors", errors);
            return handleExceptionInternal(ex, problem, headers, status, request);
        }

        @Override
        protected ResponseEntity<Object> handleHandlerMethodValidationException(
                HandlerMethodValidationException ex, HttpHeaders headers,
                HttpStatusCode status, WebRequest request) {
            ProblemDetail problem = ex.getBody();
            List<String> errors = ex.getAllErrors().stream()
                    .map(e -> e.getDefaultMessage())
                    .toList();
            problem.setProperty("errors", errors);
            return handleExceptionInternal(ex, problem, headers, status, request);
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static void send(String method, String path, String json) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        if (json != null) {
            request.header("Content-Type", "application/json")
                   .method(method, BodyPublishers.ofString(json));
        }
        HttpResponse<String> r = HTTP.send(request.build(), BodyHandlers.ofString());
        System.out.println(method + " " + path + (json == null ? "" : " " + json));
        System.out.println("  " + r.statusCode() + " " + r.body());
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(ValidationErrors.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            send("POST", "/signups", "{\"name\":\"Ana\",\"email\":\"ana@example.com\",\"age\":30}");
            send("POST", "/signups", "{\"name\":\" \",\"email\":\"not-an-email\",\"age\":15}");
            send("GET", "/signups?size=10", null);
            send("GET", "/signups?size=500", null);
        }
    }
}
Output
POST /signups {"name":"Ana","email":"ana@example.com","age":30}
  200 welcome Ana
POST /signups {"name":" ","email":"not-an-email","age":15}
  400 {"detail":"Invalid request content.","instance":"/signups","status":400,"title":"Bad Request","errors":[{"field":"age","message":"must be greater than or equal to 18"},{"field":"email","message":"must be a well-formed email address"},{"field":"name","message":"must not be blank"}]}
GET /signups?size=10
  200 page of 10
GET /signups?size=500
  400 {"detail":"Validation failure","instance":"/signups","status":400,"title":"Bad Request","errors":["must be less than or equal to 50"]}
  • @Valid @RequestBody ran the constraints on the record. All three failed, and Spring threw MethodArgumentNotValidException, whose getBindingResult() holds one FieldError per broken rule.
  • The advice extends ResponseEntityExceptionHandler and overrides handleMethodArgumentNotValid. It starts from the exception's own ProblemDetail, which already says Invalid request content., and adds an errors list. The program sorts the list by field, because Bean Validation reports violations in no fixed order.
  • @Min(1) @Max(50) directly on the size parameter needs no @Validated on the class. Since Spring Framework 6.1, Spring MVC validates method parameters itself and throws HandlerMethodValidationException, handled here by a second override.
  • Extending ResponseEntityExceptionHandler also brings the problem detail responses for all of Spring MVC's other exceptions, so this advice does what spring.mvc.problemdetails.enabled does, plus the custom lists. Spring Boot's own problem details handler is declared with @ConditionalOnMissingBean(ResponseEntityExceptionHandler.class), so it steps aside when such an advice exists.

The messages, such as must not be blank, come from Hibernate Validator in the JVM's default locale. To control them, set a message on each constraint, or add a ValidationMessages.properties file.

Traps: catch-all handlers and filters

Two mistakes appear in many code bases: a handler for Exception that swallows Spring's own errors, and an exception thrown where no advice can see it. This program has a filter that rejects requests without an API key, and runs twice with a different advice each time:

Java
package demo.traps;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@SpringBootApplication
public class HandlerTraps {

    @RestController
    static class PingController {
        @GetMapping("/ping")
        public String ping() {
            return "pong";
        }
    }

    // Rejects requests without an API key, before Spring MVC sees them
    @Component
    static class ApiKeyFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {
            if (request.getHeader("X-Api-Key") == null) {
                throw new SecurityException("missing API key");
            }
            chain.doFilter(request, response);
        }
    }

    @RestControllerAdvice
    @ConditionalOnProperty(name = "advice", havingValue = "catch-all")
    static class CatchAll {
        @ExceptionHandler(Exception.class)
        public ProblemDetail any(Exception e) {
            return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR,
                    "Unexpected " + e.getClass().getSimpleName());
        }

        @ExceptionHandler(SecurityException.class)
        public ProblemDetail denied(SecurityException e) {
            return ProblemDetail.forStatusAndDetail(HttpStatus.UNAUTHORIZED, e.getMessage());
        }
    }

    @RestControllerAdvice
    @ConditionalOnProperty(name = "advice", havingValue = "standard-first")
    static class StandardFirst extends ResponseEntityExceptionHandler {
        @ExceptionHandler(Exception.class)
        public ProblemDetail any(Exception e) {
            return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR,
                    "Unexpected " + e.getClass().getSimpleName());
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();

    static void call(String base, String method, String path, boolean key) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
                .method(method, BodyPublishers.noBody());
        if (key) {
            request.header("X-Api-Key", "k1");
        }
        HttpResponse<String> r = HTTP.send(request.build(), BodyHandlers.ofString());
        String body = r.body().replaceAll("\"timestamp\":\"[^\"]+\"", "\"timestamp\":\"...\"");
        System.out.println(method + " " + path + (key ? "" : " (no key)") + " -> "
                + r.statusCode() + " " + body);
    }

    static void run(String advice) throws Exception {
        System.out.println("=== advice: " + advice);
        try (var context = new SpringApplicationBuilder(HandlerTraps.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF", "advice=" + advice)
                .run()) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            String base = "http://localhost:" + port;
            call(base, "GET", "/ping", true);
            call(base, "GET", "/pong", true);
            call(base, "POST", "/ping", true);
            call(base, "GET", "/ping", false);
        }
    }

    public static void main(String[] args) throws Exception {
        run("catch-all");
        run("standard-first");
    }
}
Output
=== advice: catch-all
GET /ping -> 200 pong
GET /pong -> 500 {"detail":"Unexpected NoResourceFoundException","instance":"/pong","status":500,"title":"Internal Server Error"}
POST /ping -> 500 {"detail":"Unexpected HttpRequestMethodNotSupportedException","instance":"/ping","status":500,"title":"Internal Server Error"}
GET /ping (no key) -> 500 {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/ping"}
=== advice: standard-first
GET /ping -> 200 pong
GET /pong -> 404 {"detail":"No static resource pong.","instance":"/pong","status":404,"title":"Not Found"}
POST /ping -> 405 {"detail":"Method 'POST' is not supported.","instance":"/ping","status":405,"title":"Method Not Allowed"}
GET /ping (no key) -> 500 {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/ping"}
  • With the catch-all advice, the unknown path /pong returned 500 instead of 404, and POST /ping returned 500 instead of 405. Spring MVC signals these with exceptions, NoResourceFoundException and HttpRequestMethodNotSupportedException. The ExceptionHandlerExceptionResolver runs before the resolver that would map them, so @ExceptionHandler(Exception.class) caught them first. Clients then see a server error for their own mistakes, and monitoring reports outages that are not there.
  • With the standard-first advice, which extends ResponseEntityExceptionHandler, the same requests returned 404 and 405 again. The parent class has a handler for each of Spring MVC's exceptions, and these are more specific than Exception, so they win. Only exceptions it does not know about reach the catch-all.
  • In both runs, the request without a key returned 500 in the /error format, and the SecurityException handler in the first advice never ran. The filter runs before the DispatcherServlet, so the exception passed through no exception resolver at all. Tomcat caught it and forwarded to /error.

To return a proper response from a filter, write it there: set the status, the content type and the body on the HttpServletResponse, and do not call the rest of the chain. Spring Security works this way, with its own entry points for 401 and 403. Filters are covered in Spring Boot filters.

One more limit applies to every handler. An exception thrown after the response has been committed, for example halfway through streaming a large body, cannot change the status any more, because the status line was already sent.

Choosing an approach

Error handling options in Spring Boot
NeedUse
One consistent error format for the whole APIA @RestControllerAdvice extending ResponseEntityExceptionHandler, returning ProblemDetail
Problem details for Spring's own errors, with no codespring.mvc.problemdetails.enabled=true
A quick failure with a status inside a methodResponseStatusException
A domain error that always means one responseA subclass of ErrorResponseException
A domain error kept free of HTTPA plain exception, mapped in the advice
A rule for one controller only@ExceptionHandler inside that controller
All field errors in one responseOverride handleMethodArgumentNotValid
Errors in filtersWrite the response in the filter itself
Messages in the default body during developmentspring.web.error.include-message=always

Avoid @ResponseStatus on exception classes when you use problem details, since it bypasses them, and never add a handler for Exception without the standard handlers in front of it. For how controllers produce the normal responses that these errors replace, see Spring Boot @RestController.