Spring Boot Exception Handling, Tested Against Every Failure a Caller Sees

Put a @RestControllerAdvice class that extends ResponseEntityExceptionHandler in your application, add an @ExceptionHandler for each of your own exceptions, and log inside the catch-all Exception handler. Run against twelve failing requests on Spring Boot 4.1.1, a plain catch-all advice turned a 405, three 404s and four 400s into 500s and logged none of them. With two advices, the order of beans, not the most specific type, decided which one ran.

Most Spring Boot exception handling examples show one @RestControllerAdvice, one custom exception, one clean 404, and stop. The trouble is the exceptions they never throw: Spring's own, the ones raised before your controller runs, and the ones two handlers both claim.

So this article throws all of them. One small Spring Boot 4.1.1 application (Spring Framework 7.0.9, Tomcat 11.0.24, Java 25), twelve requests that fail in different ways, and the same twelve curled again under each handler setup below. Every status, body and log line below was captured from it, with timestamps shortened to ....

Twelve ways to fail, with no handler at all

The controller is deliberately a collection of mistakes. To follow along, create a Spring Boot project with the web and validation dependencies.

@RestController
@RequestMapping("/orders")
public class OrderController {

    @GetMapping("/{id}")
    public Map<String, Object> byId(@PathVariable long id) {
        if (id == 7) return Map.of("id", 7, "sku", "BOOK-1");
        throw new OrderNotFoundException(id);          // extends RuntimeException
    }

    @GetMapping("/archived/{id}")
    public Map<String, Object> archived(@PathVariable long id) {
        throw new OrderGoneException(id);              // annotated @ResponseStatus(NOT_FOUND)
    }

    @GetMapping("/{id}/total")
    public Map<String, Object> total(@PathVariable long id) {
        String coupon = null;
        return Map.of("total", coupon.length());       // a real bug
    }

    @GetMapping
    public Map<String, Object> search(@RequestParam @Min(1) @Max(100) int limit) {
        return Map.of("limit", limit);
    }
    // plus: a ResponseStatusException endpoint and a @Valid @RequestBody POST
}

Add a second controller with the same search method and @Validated on the class, and a OncePerRequestFilter that throws ResponseStatusException(HttpStatus.UNAUTHORIZED, "Unknown tenant"). With no handler of any kind:

Request What happens in the code Status
GET /orders/42 OrderNotFoundException 500
GET /orders/archived/42 @ResponseStatus(NOT_FOUND) exception 404
GET /orders/rse/42 ResponseStatusException(NOT_FOUND) 404
GET /orders/7/total NullPointerException 500
POST /orders bad fields @Valid fails 400
POST /orders truncated JSON unreadable body 400
GET /orders?limit=0 @Min(1) on a parameter 400
GET /orders?limit=abc type mismatch 400
GET /legacy/orders?limit=0 same, class-level @Validated 500
DELETE /orders/7 no such method 405
GET /nope no such path 404
filter throws a 401 exception before the controller 500

Every one of them has the same body shape, {"timestamp":"...","status":500,"error":"Internal Server Error","path":"/orders/42"}. Of the bold rows, only the first is expected.

What the log says when nothing handles it

The other half is what an on-call engineer can find afterwards, and the defaults are uneven:

ERROR ... Servlet.service() for servlet [dispatcherServlet] ... threw exception [Request processing failed: com.example.orders.OrderNotFoundException: No order with id 42] with root cause
WARN  ... DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' is not supported]

The 500s get an ERROR with a full stack trace. The bad body, the truncated JSON, the type mismatch and the 405 each got a one-line WARN. The two 404s raised by the application, the limit=0 rejection and the unknown path produced no log line at all.

The catch-all handler that turns a 405 into a 500

The handler most tutorials give you looks like this:

@RestControllerAdvice
public class CatchAllAdvice {

    @ExceptionHandler(OrderNotFoundException.class)
    public ProblemDetail notFound(OrderNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ProblemDetail anything(Exception ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");
    }
}

Returning a ProblemDetail gives an RFC 9457 body with Content-Type: application/problem+json, and GET /orders/42 now answers correctly:

{"detail":"No order with id 42","instance":"/orders/42","status":404,"title":"Not Found"}

Inside one class, the most specific handler won, as the framework documentation describes. Now look at everything else. Of the twelve requests, eleven returned 500, ten of them from the catch-all itself, including DELETE /orders/7, which lost its 405 and its Allow: GET header:

{"detail":"Something went wrong","instance":"/orders/7","status":500,"title":"Internal Server Error"}

The unknown path, bad JSON, both validation failures and both deliberate 404s went the same way: Exception.class matches Spring's exceptions too, and wins before Spring's default resolvers run.

The log is worse. The NullPointerException in /orders/7/total returned 500 and wrote nothing. Once an @ExceptionHandler method handles something, Spring treats it as handled, and your handler is the only place a log line can come from.

Common mistake

A catch-all @ExceptionHandler(Exception.class) in a plain @RestControllerAdvice. Every client error becomes a server error, and the real bug is not in the log.

Extend ResponseEntityExceptionHandler, and log the rest

ResponseEntityExceptionHandler already has handlers for Spring MVC's exceptions and for any ErrorResponseException, the parent of ResponseStatusException. Extending it puts those handlers in the same class as your catch-all, where the more specific ones win:

@RestControllerAdvice
public class ApiErrors extends ResponseEntityExceptionHandler {

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

    @ExceptionHandler(OrderNotFoundException.class)
    public ProblemDetail notFound(OrderNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

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

The same twelve requests, side by side:

Request No handler Catch-all advice ApiErrors
OrderNotFoundException 500 404 404
@ResponseStatus(NOT_FOUND) 404 500 500
ResponseStatusException 404 404 500 404
NullPointerException 500 500 500
bad fields / truncated JSON 400 / 400 500 / 500 400 / 400
limit=0 / limit=abc 400 / 400 500 / 500 400 / 400
class-level @Validated 500 500 500
DELETE / unknown path 405 / 404 500 / 500 405 / 404
filter throws 401 500 500 500

Every Spring status came back, and the unexpected exceptions now log ERROR ... com.example.orders.ApiErrors : Unhandled exception with the trace. One row is still wrong: OrderGoneException, annotated @ResponseStatus(HttpStatus.NOT_FOUND), returned 500. ResponseEntityExceptionHandler does not look at that annotation, and your Exception handler claims the exception first. If you keep a catch-all, give those exceptions a handler of their own or throw ResponseStatusException instead.

Two advices: the most specific handler does not win

Split the handlers across two classes, as a growing codebase eventually does:

@RestControllerAdvice
public class AnyErrorAdvice {
    @ExceptionHandler(RuntimeException.class)            // -> 500
    public ProblemDetail anything(RuntimeException ex) { ... }
}

@RestControllerAdvice
public class OrderErrorAdvice {
    @ExceptionHandler(OrderNotFoundException.class)      // -> 404, the exact type
    public ProblemDetail notFound(OrderNotFoundException ex) { ... }
}

GET /orders/42:

{"detail":"handled by AnyErrorAdvice","instance":"/orders/42","status":500,"title":"Internal Server Error"}

The exact match lost. Spring asks each advice in turn, and the first one that has any matching method handles the exception. The documentation says so, in a sentence that is easy to skim past: "a cause match on a higher-priority @ControllerAdvice bean is preferred to any match" on a lower-priority one.

Neither class declared a priority. Renaming AnyErrorAdvice to RuntimeErrorAdvice, changing nothing else, flipped the result to 404 handled by OrderErrorAdvice. In both runs the class whose name sorted first won, but that is scan order rather than a rule, and a rename in an unrelated pull request is enough to change your API's status codes. Adding @Order(Ordered.HIGHEST_PRECEDENCE) to the specific advice made it win regardless of name.

The general advice also caught ResponseStatusException, HandlerMethodValidationException and the type-mismatch and unreadable-body exceptions, all RuntimeExceptions, and made them 500s. The checked MethodArgumentNotValidException, HttpRequestMethodNotSupportedException and NoResourceFoundException kept their 400, 405 and 404.

An exception thrown in a filter never reaches your advice

The filter throws ResponseStatusException with 401. Under every setup above, including ApiErrors, the caller received:

{"timestamp":"...","status":500,"error":"Internal Server Error","path":"/orders/7"}

Filters run before the DispatcherServlet, and advice is applied inside it. The exception goes up to Tomcat, which records a 500 and forwards to Spring Boot's /error page without reading the status inside the exception. Turning on spring.mvc.problemdetails.enabled changed nothing either, because that property configures a handler that also lives inside the DispatcherServlet.

Two changes to the filter got the 401 through:

// 1. Set the status yourself: 401, default /error body
response.sendError(401, "Unknown tenant");
return;

// 2. Hand the exception to the same resolvers your advice uses
resolver.resolveException(request, response, null,
        new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Unknown tenant"));
return;

resolver is the HandlerExceptionResolver bean named handlerExceptionResolver, injected with @Qualifier. With ApiErrors in place, option 2 returned 401 with Content-Type: application/problem+json and {"detail":"Unknown tenant","instance":"/orders/7","status":401,"title":"Unauthorized"}, the same shape as every other error. If your filter is an authentication check, securing the API with Spring Security's JWT support avoids writing that filter in the first place.

Two validation exceptions, and the @Validated that makes one a 500

A failed @Valid @RequestBody raises MethodArgumentNotValidException. A constraint written directly on a parameter, like @Min(1) int limit, raises HandlerMethodValidationException. The validation reference is explicit that applications should handle both.

So if you overrode only handleMethodArgumentNotValid to return field errors, as in the REST API walkthrough, the body POST names its fields and GET /orders?limit=0 still answered:

{"detail":"Validation failure","instance":"/orders","status":400,"title":"Bad Request"}

Overriding handleHandlerMethodValidationException as well, and reading ex.getParameterValidationResults(), produced "errors":{"limit":"must be greater than or equal to 1"}.

The bigger trap is older advice. Answers written before Spring Framework 6.1 put @Validated on the controller class so that parameter constraints work. On Spring Boot 4.1.1 they already work without it, and adding it changed the result from 400 to 500, under every handler setup tested:

ERROR ... threw exception [Request processing failed: jakarta.validation.ConstraintViolationException: search.limit: must be greater than or equal to 1]

Class-level @Validated switches validation to an AOP proxy, which throws ConstraintViolationException, and none of Spring MVC's built-in handling turned that into a 400 in any of the setups tried. The documentation's own advice is to remove the class-level annotation to use the built-in support added in Framework 6.1.

The properties that leak, and the Boot 4 rename that ignores them

Spring Boot's reference documentation describes the /error JSON as including "the HTTP status, and the exception message". By default it does not include the message, and that default is the safe one. With these three set:

spring.web.error.include-message=always
spring.web.error.include-exception=true
spring.web.error.include-stacktrace=on_param

The NullPointerException then told the caller about the code:

{"timestamp":"...","status":500,"error":"Internal Server Error","exception":"java.lang.NullPointerException",
 "message":"Cannot invoke \"String.length()\" because \"coupon\" is null","path":"/orders/7/total"}

With on_param, anyone adding ?trace=true received the full stack trace in a trace field, starting at OrderController.java:34. Keep include-message and include-stacktrace at never in production.

Note the prefix. Nearly every guide writes server.error.include-message. On Boot 4.1.1, server.error.include-message=always in application.properties did nothing: no startup warning, no error, and the message stayed out of the body. The properties appendix lists only the spring.web.error names now. Adding spring-boot-properties-migrator as a runtime dependency made the application say so on startup:

ERROR ... PropertiesMigrationListener :
The use of configuration keys that are no longer supported was found in the environment:

Property source 'Config resource 'class path resource [application.properties]' via location 'optional:classpath:/'':
	Key: server.error.include-message
		Line: 2
		Reason: Replacement key 'spring.web.error.include-message' uses an incompatible target type

Whatever the old line said, the running application uses the default.

The handler setup that survived all twelve

  • One @RestControllerAdvice extending ResponseEntityExceptionHandler, so Spring's 400, 404 and 405 survive.
  • An @ExceptionHandler for each of your own exceptions, including any marked @ResponseStatus.
  • A catch-all Exception handler that logs, because nothing else will.
  • @Order on any advice that must win, if there is more than one.
  • Filters that call sendError or the handlerExceptionResolver, never a bare throw.
  • No class-level @Validated on controllers, and overrides for both validation exceptions.
  • spring.web.error.*, not server.error.*, on Boot 4.

[!TAKEAWAY] Exception handling in Spring Boot fails quietly, not loudly. A catch-all advice answered ten of twelve failures with its own 500 and logged none of them. Across two advices, bean order beat the exact type. A filter's 401 became a 500, @Validated turned a 400 into a 500, and a renamed property meant the settings file was not describing the running application. Curl your failure paths as well as your happy ones.

Frequently asked questions

Does the most specific @ExceptionHandler always win?
Only inside one class. Across two @RestControllerAdvice beans Spring asks them in order and the first one with any matching method wins. In the test here a RuntimeException handler in one advice beat an exact OrderNotFoundException handler in another, returning 500 instead of 404, until the specific advice was given @Order(Ordered.HIGHEST_PRECEDENCE).
Why does my @RestControllerAdvice not catch exceptions thrown in a filter?
Because filters run before the DispatcherServlet, and advice is applied by the DispatcherServlet. A ResponseStatusException for 401 thrown from a OncePerRequestFilter came back as a 500 from /error. Call response.sendError, or pass the exception to the handlerExceptionResolver bean, and the status survives.
Should I catch Exception.class in a global handler?
Yes, but only in a class that extends ResponseEntityExceptionHandler, and log inside it. A plain advice with an Exception handler also catches Spring's own exceptions — method not allowed, unknown path, unreadable JSON, validation — and turns all of them into 500. Once an advice handles an exception, Spring logs nothing unless your handler does.
Why is server.error.include-message ignored in Spring Boot 4?
The server.error.include-* properties were renamed to spring.web.error.include-* in Boot 4.0. The old names are not an error at startup; they simply do nothing. Adding spring-boot-properties-migrator makes the application print the key and the line number on startup, which is the fastest way to find them after an upgrade.
Why does @Validated on my controller return 500 for a bad parameter?
Class-level @Validated routes method validation through an AOP proxy, which throws ConstraintViolationException, and Spring MVC's built-in handling did not map that to 400 in any setup tested. The same @Min(1) parameter returned 400 without the annotation and 500 with it. Spring Framework 6.1 and later validate controller parameters themselves, so the annotation should simply be removed.

References

  1. Spring Framework: Exceptions (@ExceptionHandler)Spring
  2. Spring Framework: ValidationSpring
  3. Spring Framework: Error ResponsesSpring
  4. Spring Boot Reference: Servlet Web ApplicationsSpring
  5. Spring Boot: Common Application PropertiesSpring
  6. RFC 9457: Problem Details for HTTP APIsIETF