Sub topic 11
Turning Binding and Validation Failures into 400 Responses
This chapter assumes you know the basics of Spring MVC controllers, @PathVariable, @RequestParam, @RequestBody, and @Valid. It also assumes you have a Spring Boot web project that runs. Here you will see which exceptions Spring throws when input is wrong, and how to turn them into one consistent 400 response.
What goes wrong, and which exception results
Spring binds request data before your controller method runs. If binding fails, your method is never called. Spring throws an exception instead.
| Failure | Example | Exception |
|---|---|---|
| Value cannot be converted | `GET /api/books/abc` where `id` is a `Long` | `MethodArgumentTypeMismatchException` |
| Required parameter missing | `GET /api/books/published` with no `since` | `MissingServletRequestParameterException` |
| Body fails validation | `pages` is `-5` | `MethodArgumentNotValidException` |
| Body is not readable JSON | Broken JSON, or a string where a number belongs | `HttpMessageNotReadableException` |
Spring Boot's default handling already maps these to a 400 status. The default body is not consistent across cases, though, and it may expose details you did not intend to show. A central handler fixes both problems.
A central handler with @RestControllerAdvice
A class annotated with @RestControllerAdvice applies its @ExceptionHandler methods to every controller. Returning a ProblemDetail produces a response in the standard problem format (RFC 9457) with the media type application/problem+json.
@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(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;
}
}The first handler uses ex.getName(), which is the name of the parameter that failed. The message does not echo the rejected value back to the client. The second handler collects one message per field into an errors map. putIfAbsent keeps the first message when a field breaks several constraints.
What the client sees
With the handler in place, this request:
curl -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"","author":"Ursula K. Le Guin","pages":-5}'returns a body like this:
{
"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"
}
}The exact message text depends on the validator and the locale. Do not write client code that matches on those strings. Match on the field names instead.
Common errors
- Handling only some exceptions. The handler above does not cover a missing parameter or malformed JSON. Those still return 400 through Spring's defaults, but in a different shape. For one shape everywhere, add handlers for
MissingServletRequestParameterExceptionandHttpMessageNotReadableException. Alternatively, extendResponseEntityExceptionHandler, which already covers the built-in Spring MVC exceptions and renders them asProblemDetail. - Leaking internals. Do not put
ex.getMessage()from a parse exception in the response. It can include class names or parser details. - Expecting validation on the wrong target.
@Validon@RequestBodythrowsMethodArgumentNotValidException. Constraints placed directly on@RequestParamor@PathVariableparameters are different. They need@Validatedon the controller class, and in Spring Framework 6.1 and later they raiseHandlerMethodValidationException. Handle that exception separately. - Returning 200 with an error body. Return a
ProblemDetailwith a 400 status. Clients and monitoring tools rely on the status code.
Exercise
A client sends GET /api/books/published?since=yesterday, and the controller declares @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since. Which exception is thrown, and what status does the handler in this chapter return?
Show answer
The string "yesterday" cannot be converted to a LocalDate, so Spring throws MethodArgumentTypeMismatchException before the controller method runs. The handleTypeMismatch method returns a ProblemDetail with status 400 and the detail "Invalid value for parameter 'since'".
Exercise
Why does the handleInvalidBody method use putIfAbsent when it fills the errors map?
Show answer
A field can violate several constraints at once, which produces several field errors with the same field name. putIfAbsent keeps the first message for each field, so the map has one entry per field and later messages do not overwrite it.