Sub topic 11
Turning binding and validation failures into 400 responses
This chapter assumes you have a running Spring Boot 3 web project and the controller methods from the earlier chapters. It also assumes you know the @PathVariable, @RequestParam, and @RequestBody annotations, and that you have used Bean Validation annotations such as @NotBlank and @Valid. Here you will see what Spring does when input cannot be bound or fails validation, and how to return a 400 response with a stable shape.
What happens when input is bad
Before your controller method runs, Spring tries to build every argument from the request. Any step can fail, and each failure raises a specific exception. If nothing handles it, the client gets Spring Boot's default error JSON, and some failures end up as a 500 instead of a 400.
| Situation | Exception | Default status |
|---|---|---|
| `GET /api/books/abc` where the parameter is `Long` | `MethodArgumentTypeMismatchException` | 400 |
| `?size=ten` for an `int` parameter | `MethodArgumentTypeMismatchException` | 400 |
| Required `@RequestParam` is absent | `MissingServletRequestParameterException` | 400 |
| Body is empty, or is not valid JSON | `HttpMessageNotReadableException` | 400 |
| JSON has a wrong type, such as `"pages": "many"` | `HttpMessageNotReadableException` | 400 |
| `@Valid @RequestBody` constraint fails | `MethodArgumentNotValidException` | 400 |
| Constraint on a parameter fails (Spring 6.1+) | `HandlerMethodValidationException` | 400 |
| Constraint fails with class-level `@Validated` | `ConstraintViolationException` | 500 unless handled |
| `{id}` in the mapping has no matching parameter | `MissingPathVariableException` | 500 |
The last two rows are the traps. A ConstraintViolationException is a client error, but nothing maps it to 400 for you. A MissingPathVariableException is a programming error in your mapping, so a 500 is correct and you should leave it alone.
The ProblemDetail format
Spring 6 includes ProblemDetail, a class that models the RFC 9457 "problem details" format (the successor of RFC 7807). When a handler method returns one, Spring serializes it with the content type application/problem+json. The standard fields are type, title, status, detail, and instance. You can add your own fields with setProperty, and they appear at the top level of the JSON.
A single format for every error means clients write one error parser. Use ProblemDetail unless your API already has its own error envelope. In that case, return your own type from the same handlers.
A handler for each failure
Put the handlers in one @RestControllerAdvice class. It applies to every controller in the application. Each @ExceptionHandler method names the exception it catches and returns the body to send.
package com.example.books;
import jakarta.validation.ConstraintViolationException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ProblemDetail handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Invalid value for parameter '" + ex.getName() + "'");
}
@ExceptionHandler(MissingServletRequestParameterException.class)
public ProblemDetail handleMissingParameter(MissingServletRequestParameterException ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Missing required parameter '" + ex.getParameterName() + "'");
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public ProblemDetail handleUnreadableBody(HttpMessageNotReadableException ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Request body is missing or is not valid JSON for this endpoint");
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalidBody(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request body failed validation");
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors()
.forEach(e -> errors.putIfAbsent(e.getField(), e.getDefaultMessage()));
problem.setProperty("errors", errors);
return problem;
}
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handleConstraintViolations(ConstraintViolationException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request parameters failed validation");
Map<String, String> errors = new LinkedHashMap<>();
ex.getConstraintViolations()
.forEach(v -> errors.putIfAbsent(v.getPropertyPath().toString(), v.getMessage()));
problem.setProperty("errors", errors);
return problem;
}
}Several choices here are deliberate.
errorsis a map from field name to message.putIfAbsentkeeps the first message when one field breaks several constraints. AListof messages per field is a reasonable alternative if clients want all of them.- The ordering is stable.
LinkedHashMapkeeps the order in which Spring reports the errors, which makes responses easier to compare in tests. - The unreadable-body message is fixed text. The message from
HttpMessageNotReadableExceptionoften contains Jackson internals such as Java class names and line numbers. Log it on the server if you need it, but do not send it to the client. - The type-mismatch message names the parameter only.
ex.getName()is the parameter name. Echoing the rejected value is possible withex.getValue(), but then you return attacker-controlled text. If you do, keep it short and let the client treat it as plain text.
What the client sees
Run the application with the advice class in place and send an invalid body:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"","author":"Ursula K. Le Guin","pages":-5}'The response looks like this, with the fields in errors appearing in the order Spring reports them:
HTTP/1.1 400
Content-Type: application/problem+json
{"type":"about:blank","title":"Bad Request","status":400,"detail":"Request body failed validation","instance":"/api/books","errors":{"title":"must not be blank","pages":"must be greater than 0"}}Spring fills in title, type, and instance for you. The type value about:blank means "no extra meaning beyond the HTTP status". If you want clients to branch on error kind, call problem.setType(URI.create("https://example.com/problems/validation")) and publish documentation at that address.
A malformed query value produces a smaller body:
curl -i "http://localhost:8080/api/books?size=ten"HTTP/1.1 400
Content-Type: application/problem+json
{"type":"about:blank","title":"Bad Request","status":400,"detail":"Invalid value for parameter 'size'","instance":"/api/books"}Validation on path and query parameters
Constraints placed directly on controller parameters, such as @Positive @PathVariable Long id or @Max(100) @RequestParam int size, fail in one of two ways, and the way depends on your setup.
- Spring 6.1 and later (Spring Boot 3.2+), no
@Validatedon the controller. Spring's built-in method validation applies, and a failure raisesHandlerMethodValidationException. Spring maps it to 400 only through its default handling. @Validatedon the controller class. The older proxy-based validation applies, and a failure raisesConstraintViolationException. That is the exception the handler above catches.
If you rely on the new built-in behavior, add a handler for HandlerMethodValidationException as well, so those responses have the same shape as the others. Its getParameterValidationResults() method returns the failing parameters and their messages.
For ConstraintViolationException, the key in errors is the property path, for example getById.id. Without the -parameters compiler flag, it can be getById.arg0. Spring Boot's Maven and Gradle plugins turn -parameters on, so this normally works. Check it in a test.
Gotchas
- Handler ambiguity. If you extend
ResponseEntityExceptionHandler, it already handles most of the exceptions above. Declaring a second@ExceptionHandlerfor the same exception in the same class fails at startup with an "Ambiguous @ExceptionHandler method" error. Override the protectedhandle...methods instead. - Boot's own problem-detail switch. Setting
spring.mvc.problemdetails.enabled=trueregisters a built-in advice that returnsProblemDetailfor the standard Spring MVC exceptions. If you write your own advice as well, add@Order(Ordered.HIGHEST_PRECEDENCE)to yours so it wins. - Wrong content type. A request with no
Content-Type: application/jsonheader fails withHttpMediaTypeNotSupportedException, which is a 415, not a 400. That status is correct, so leave it. - Unknown JSON fields. Spring Boot configures Jackson to ignore unknown properties, so a typo such as
"titel"does not cause a binding error. It surfaces as a missing-field validation error ontitleif that field has@NotBlank. - Catch-all handlers. Do not add
@ExceptionHandler(Exception.class)that returns 400. It hides real server bugs as client errors.
Exercise
A controller method declares @GetMapping("/{id}") Book get(@PathVariable Long id). A client calls GET /api/books/abc. Which exception is raised, which status does the client receive when your advice has a handler for it, and which status would a missing @PathVariable parameter (the mapping has {id} but the method has no matching parameter) produce?
Show answer
MethodArgumentTypeMismatchException is raised, because "abc" cannot be converted to Long. A handler that returns a 400 ProblemDetail sends 400. A mapping with {id} but no matching parameter raises MissingPathVariableException, which is a server-side mistake and produces 500.
Exercise
A class-level @Validated controller has @GetMapping("/{id}") Book get(@PathVariable @Positive Long id). A client calls GET /api/books/-3. Without a dedicated handler, what status does the client get, and what do you add to the advice class to return a 400 with an errors map?
Show answer
ConstraintViolationException is raised and nothing maps it to 400, so the client gets 500. Add an @ExceptionHandler(ConstraintViolationException.class) method that returns a ProblemDetail with status 400, and fill an errors property from ex.getConstraintViolations() using each violation's property path and message.
Exercise
Why does the handler for HttpMessageNotReadableException return fixed text instead of ex.getMessage()?
Show answer
The exception message usually contains Jackson internals such as Java class names, field paths, and source locations. Sending that to clients leaks implementation details and gives a message that changes between library versions. Log the exception on the server and return a stable message.