Sub topic 5
What happens when validation fails
This chapter assumes you can write a Spring MVC controller, have a request DTO with constraint annotations, and have added @Valid to a @RequestBody parameter. It follows a failed validation from the moment the constraint is violated to the HTTP response, and it names the exception types you will meet on the way. The next chapter covers shaping the response body.
The behavior described here is for Spring Boot 3.2 or later (Spring Framework 6.1 or later). Earlier versions lack HandlerMethodValidationException, which changes which exception you see.
Validation runs before your method does
Bean Validation does not run inside your controller method. Spring runs it while it prepares the method's arguments. The sequence for a @Valid @RequestBody parameter is:
- The
DispatcherServletpicks the handler method. - An argument resolver reads the JSON body and converts it to the DTO with Jackson.
- If the parameter has
@Validor@Validated, the resolver runs the validator on the DTO. - If there are violations, the resolver throws an exception. The controller method is never called.
- The exception goes to the exception resolvers, which turn it into a response.
Two consequences follow. Your method body can assume a validated object, and a failure produces no side effects from your code. Also, validation is a separate step from parsing. A body that is not valid JSON, or that has a wrong type such as "age": "abc" for an Integer, fails in step 2 and never reaches validation.
The exception types
Four exceptions cover almost every failure. Which one you get depends on what you annotated and where.
| Exception | Raised when | Default status |
|---|---|---|
| `HttpMessageNotReadableException` | The body is malformed JSON or has a type mismatch. Validation never ran. | 400 |
| `MethodArgumentNotValidException` | A `@Valid` or `@Validated` `@RequestBody` (or `@ModelAttribute`) object has violations. | 400 |
| `HandlerMethodValidationException` | A method parameter has its own constraints, such as `@RequestParam @Min(1)`, and the class has no `@Validated`. | 400 |
| `ConstraintViolationException` | A class annotated `@Validated` is validated through an AOP proxy and a constraint fails. | 500 |
MethodArgumentNotValidException
This is the common case for request bodies. It carries a BindingResult that holds one FieldError for each violated field constraint and one ObjectError for each violated class-level constraint.
A single request can violate several constraints at once, and Spring reports them together. Posting {"name": "", "email": "nope", "age": 3} to the CreateUserRequest from the earlier chapter produces three field errors, not one. The same field can also appear twice. A blank email fails both @NotBlank and @Email, so getFieldErrors() returns two entries for it.
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
public final class FieldErrorPrinter {
private FieldErrorPrinter() {
}
public static void print(MethodArgumentNotValidException ex) {
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
System.out.printf("%s: %s (rejected value: %s, code: %s)%n",
error.getField(),
error.getDefaultMessage(),
error.getRejectedValue(),
error.getCode());
}
ex.getBindingResult().getGlobalErrors()
.forEach(error -> System.out.println("object: " + error.getDefaultMessage()));
}
}getCode() returns the constraint name, for example NotBlank or Min. It is useful when you map errors to your own error codes. getRejectedValue() is the value the client sent. Be careful about echoing it back, because it can contain passwords or other sensitive input.
HandlerMethodValidationException
Before Spring 6.1, a constraint placed directly on a parameter did nothing unless the class had @Validated. From 6.1, Spring validates such parameters itself. Take this method:
@GetMapping("/orders")
public String list(@RequestParam @Min(1) int page) {
return "page " + page;
}If page=0 is sent, Spring throws HandlerMethodValidationException. The exception holds one result per validated parameter. A result can describe a request parameter, a path variable, a header or a body.
This exception also appears in a case that surprises people. A method that has @Valid @RequestBody alone throws MethodArgumentNotValidException. If you add any other constraint to a parameter of the same method, validation of the whole method switches to the built-in method validation, and a violated body constraint is then reported as HandlerMethodValidationException. Your existing handler for MethodArgumentNotValidException then stops matching.
ConstraintViolationException
This exception comes from Bean Validation itself, not from Spring MVC. Class-level @Validated makes Spring wrap the bean in an AOP proxy. A MethodValidationInterceptor on the proxy validates arguments, and return values, on every call. The interceptor throws the standard Jakarta ConstraintViolationException, which holds a set of ConstraintViolation objects.
The OrderController in the spine uses this style, so GET /orders/0 throws this exception. Property paths have the form method.argument:
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
public final class ViolationPrinter {
private ViolationPrinter() {
}
public static void print(ConstraintViolationException ex) {
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
System.out.printf("%s: %s (invalid value: %s)%n",
violation.getPropertyPath(), // for example "find.id"
violation.getMessage(),
violation.getInvalidValue());
}
}
}The path find.id uses the Java method name and parameter name. Reporting it as-is leaks internal names to the client, and it often differs from the name the client used, such as a query parameter named page. Parameter names are available only if the code is compiled with -parameters. Spring Boot's Maven and Gradle plugins enable this. Otherwise you see arg0.
When a class has @Validated, Spring skips the built-in method validation for it and the AOP proxy handles validation instead. That is why a class with @Validated produces ConstraintViolationException and a class without it produces HandlerMethodValidationException.
Default responses without a handler
If you write no handler, the outcome depends on the exception:
MethodArgumentNotValidException,HandlerMethodValidationExceptionandHttpMessageNotReadableExceptionare handled by Spring'sDefaultHandlerExceptionResolverandResponseStatusExceptionResolver. The status is 400.- With Spring Boot's defaults, the body is the generic
/errorJSON withtimestamp,status,error, andpath. The list of field errors is not included, becauseserver.error.include-binding-errorsdefaults tonever. ConstraintViolationExceptionis not recognized by any Spring MVC resolver. It propagates out of the servlet and the client gets a 500 Internal Server Error. A client mistake is reported as a server error, and your monitoring will count it as one.
The 500 for ConstraintViolationException is the most common bug in this area. The fix is a handler that maps it to 400:
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ConstraintViolationAdvice {
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handle(ConstraintViolationException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid request parameters");
}
}This handler discards the details on purpose. Building a useful error body is the subject of the next chapter.
Choosing an approach for parameters
Both ways of validating parameters work. They differ in what you must handle.
| Approach | Exception | Notes |
|---|---|---|
| No `@Validated`, constraints on parameters | `HandlerMethodValidationException` | Returns 400 by default. Spring Framework 6.1 or later is required. |
| Class-level `@Validated` | `ConstraintViolationException` | Returns 500 by default and needs your handler. It also works on non-controller beans, such as services. |
For new controller code on Boot 3.2 or later, omitting @Validated gives a correct default status. Keep @Validated for service beans, where there is no MVC machinery.
Edge cases
- Order of errors. The set of violations has no guaranteed order. If you need stable output, sort by field name before you build the response.
- Fail-fast. By default, Hibernate Validator collects all violations. It does not stop at the first one. You can change this with a custom validator factory configured with
hibernate.validator.fail_fast, but most APIs prefer reporting everything at once. - Null body. A missing body with
@RequestBody(required by default) raisesHttpMessageNotReadableException. It does not reach validation.@NotNullon fields only matters when a body object exists. - Constraint on a type conversion failure. A request such as
?page=abcfor anintparameter fails withMethodArgumentTypeMismatchException(400) before constraints are checked.
Exercise
A controller class has no @Validated. One method is create(@Valid @RequestBody CreateUserRequest request, @RequestParam @Min(1) int version). A request with a valid body and version=0 arrives. Which exception is thrown, and what status does the client see with no custom handlers? What changes if you add class-level @Validated?
Show answer
Because the method has a constraint on a parameter besides the @Valid body, Spring uses built-in method validation and throws HandlerMethodValidationException, which the default resolver maps to 400. With class-level @Validated, the AOP proxy validates the call and throws ConstraintViolationException. No Spring MVC resolver handles it, so the client gets a 500 unless you add an @ExceptionHandler for it.
Exercise
A client posts {"name": "Ana", "email": "[email protected]", "age": "twenty"} to an endpoint that accepts CreateUserRequest. Does Bean Validation produce a violation for age? Which exception results?
Show answer
No. Jackson cannot convert "twenty" to Integer, so deserialization fails before validation runs. The exception is HttpMessageNotReadableException, mapped to 400. The @NotNull and @Min constraints on age are never evaluated.