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 trycatch
The exception passes through two layers, and knowing which one handled it explains most surprises:
- Spring MVC's exception resolvers: the
catches the exception and offers it to a chain ofDispatcherServlet beans, in order. The first one that returns a result decides the response.HandlerExceptionResolver - The servlet container's error page: if no resolver handles the exception, or a resolver only calls
, Tomcat forwards the request to the error path. Spring Boot mapsresponse.sendError(status) to its/error , which writes the JSON body withBasicErrorController ,timestamp ,status anderror .path
| Resolver | Handles | Response |
|---|---|---|
ExceptionHandlerExceptionResolver | Exceptions with a matching @ExceptionHandler@ControllerAdvice | Whatever the handler returns |
ResponseStatusExceptionResolver | ResponseStatusException@ResponseStatus | sendError/error |
DefaultHandlerExceptionResolver | Spring MVC's own exceptions: missing parameter, wrong method, unsupported media type, no handler | sendError |
| None of them | Everything else, such as IllegalStateException | 500, 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+jsontypetitlestatusdetailinstanceProblemDetailErrorResponse
All programs on this page use Spring Boot 4.1 with Spring Framework 7.0 and spring-boot-starter-webmvcspring-boot-starter-validationlogging.level.root=OFF
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
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");
}
}
=== 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 the defaults, all four responses have the same shape, produced by
after aBasicErrorController . Even the message ofsendError is missing: Spring Boot leaves out exception messages by default, so that internal details such as SQL errors do not leak to clients.ResponseStatusException(NOT_FOUND, "no order 7") - With
, the 404 and 405 becamespring.mvc.problemdetails.enabled=true with a usefulapplication/problem+json , such asdetail . Spring Boot registered ano order 7 , which answers Spring MVC's own exceptions andResponseEntityExceptionHandler exceptions directly, without going throughErrorResponse ./error - The
still produced the old shape in both runs. Problem details only apply to exceptions Spring knows; everything else still ends atIllegalStateException , and needs a handler of your own if clients should see one format./error
Running the first configuration with spring.web.error.include-message=always"message":"database is down""message":"no order 7"server.error.*spring.web.error.*
@ExceptionHandler and @RestControllerAdvice
An @ExceptionHandler@RestControllerAdvice
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");
}
}
}
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"}
matched three handlers in the advice: its own type, its parentOrderNotFoundException , andNotFoundException . Spring chose the closest type in the class hierarchy, so the response carries the customRuntimeException ,title and the extratype property.orderId- The customer's plain
went to theNotFoundException handler. Its title is the default for 404,missing .Not Found - Both
methods threw the sameinvoice , but the results differ. InUnsupportedOperationException , the controller's own handler won over the advice and returned 501 as plain text. InOrderController , which has no handler, the advice'sCustomerController handler returned 500.RuntimeException - Spring filled in
with the request path in everyinstance , and set the content type toProblemDetail , even though no handler set either.application/problem+json
The handlers take the exception type from their parameter, so @ExceptionHandlerHandlerMethodLocaleProblemDetailResponseEntity@Order@RestControllerAdvice(basePackages = "com.example.api")
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:
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");
}
}
}
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}
gave 409, but in the old@ResponseStatus(code = CONFLICT, reason = "Seat already taken") format, without the reason. The annotation makes/error callResponseStatusExceptionResolver , so problem details do not apply to it. This makes the annotation the weakest of the three choices.sendError gave 400 with its message asResponseStatusException . It implementsdetail , so the problem details handler answered it directly.ErrorResponse extendsInsufficientFundsException and builds its wholeErrorResponseException , with a title and two extra properties. The client got status 422 and the propertiesProblemDetail andbalance it can act on.price
HttpStatus.UNPROCESSABLE_CONTENTUNPROCESSABLE_ENTITYErrorResponseException
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:
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);
}
}
}
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"]}
ran the constraints on the record. All three failed, and Spring threw@Valid @RequestBody , whoseMethodArgumentNotValidException holds onegetBindingResult() per broken rule.FieldError- The advice extends
and overridesResponseEntityExceptionHandler . It starts from the exception's ownhandleMethodArgumentNotValid , which already saysProblemDetail , and adds anInvalid request content. list. The program sorts the list by field, because Bean Validation reports violations in no fixed order.errors directly on the@Min(1) @Max(50) parameter needs nosize on the class. Since Spring Framework 6.1, Spring MVC validates method parameters itself and throws@Validated , handled here by a second override.HandlerMethodValidationException- Extending
also brings the problem detail responses for all of Spring MVC's other exceptions, so this advice does whatResponseEntityExceptionHandler does, plus the custom lists. Spring Boot's own problem details handler is declared withspring.mvc.problemdetails.enabled , so it steps aside when such an advice exists.@ConditionalOnMissingBean(ResponseEntityExceptionHandler.class)
The messages, such as must not be blankmessageValidationMessages.properties
Traps: catch-all handlers and filters
Two mistakes appear in many code bases: a handler for Exception
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");
}
}
=== 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
advice, the unknown pathcatch-all returned 500 instead of 404, and/pong returned 500 instead of 405. Spring MVC signals these with exceptions,POST /ping andNoResourceFoundException . TheHttpRequestMethodNotSupportedException runs before the resolver that would map them, soExceptionHandlerExceptionResolver caught them first. Clients then see a server error for their own mistakes, and monitoring reports outages that are not there.@ExceptionHandler(Exception.class) - With the
advice, which extendsstandard-first , 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 thanResponseEntityExceptionHandler , so they win. Only exceptions it does not know about reach the catch-all.Exception - In both runs, the request without a key returned 500 in the
format, and the/error handler in the first advice never ran. The filter runs before theSecurityException , so the exception passed through no exception resolver at all. Tomcat caught it and forwarded toDispatcherServlet ./error
To return a proper response from a filter, write it there: set the status, the content type and the body on the HttpServletResponse
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
| Need | Use |
|---|---|
| One consistent error format for the whole API | A @RestControllerAdviceResponseEntityExceptionHandlerProblemDetail |
| Problem details for Spring's own errors, with no code | spring.mvc.problemdetails.enabled=true |
| A quick failure with a status inside a method | ResponseStatusException |
| A domain error that always means one response | A subclass of ErrorResponseException |
| A domain error kept free of HTTP | A plain exception, mapped in the advice |
| A rule for one controller only | @ExceptionHandler |
| All field errors in one response | Override handleMethodArgumentNotValid |
| Errors in filters | Write the response in the filter itself |
| Messages in the default body during development | spring.web.error.include-message=always |
Avoid @ResponseStatusException