Sub topic 5
What happens when validation fails
This chapter assumes you can write a Spring MVC controller and have added spring-boot-starter-validation. You should also know the @Valid and @Validated annotations from the previous chapter. Here you will learn which exception each kind of failure raises and what Spring does with it if you don't handle it.
Validation failures are exceptions
A failed constraint never returns a value to your controller. Spring stops the request and throws an exception. Which exception depends on where the constraint sits and how validation was triggered.
The three exception types
| Exception | Raised when | Default status |
|---|---|---|
| `MethodArgumentNotValidException` | A `@Valid @RequestBody` object has violations | 400 |
| `ConstraintViolationException` | A parameter constraint fails on a class annotated with `@Validated` | 500 |
| `HandlerMethodValidationException` | A parameter constraint fails on a controller without `@Validated` (Spring Framework 6.1 and later) | 400 |
HttpMessageNotReadableException is a related case. It happens earlier, when the body is not valid JSON or a value has the wrong type. No constraint runs, because the DTO was never built.
Reading the exception
MethodArgumentNotValidException carries a BindingResult. Each violated constraint becomes a FieldError with the field name, the rejected value and the message.
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
public final class ViolationPrinter {
private ViolationPrinter() {
}
public static void print(MethodArgumentNotValidException ex) {
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
System.out.printf("%s: %s (rejected value: %s)%n",
error.getField(), error.getDefaultMessage(), error.getRejectedValue());
}
}
}ConstraintViolationException works differently. It is a Jakarta Validation type, not a Spring one. Call getConstraintViolations() to get a set of ConstraintViolation objects. Each one has a property path such as find.id, which includes the method name, and a message.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
public final class ConstraintPrinter {
private ConstraintPrinter() {
}
public static void print(ConstraintViolationException ex) {
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
}
}
}What the client sees by default
For a body failure, Spring's DefaultHandlerExceptionResolver sets status 400. Spring Boot's /error endpoint then builds the response. It hides the violation details unless you set server.error.include-binding-errors=always. Even then, the output is a generic error structure, not one you designed.
The 500 for ConstraintViolationException is the bigger problem. A client who sent /orders/0 made a mistake, but the server reports a failure of its own. Dashboards and alerts then count it as a server error.
Why the type matters
Each exception exposes its violations through a different API, so you need a separate handler for each. You can map every type to the same 400 response body. Clients then see one error format whatever the source. The next chapter builds that with @RestControllerAdvice and ProblemDetail.
Exercise
A controller is annotated with @Validated and has the method find(@PathVariable @Min(1) long id). A client calls /orders/0 and no exception handler exists. Which exception is thrown, and what status does the client receive?
Show answer
ConstraintViolationException is thrown. Nothing maps it to a client error, so the client receives status 500. A dedicated @ExceptionHandler is needed to turn it into a 400.
Exercise
Why does a request with malformed JSON never produce a MethodArgumentNotValidException?
Show answer
Parsing fails first and throws HttpMessageNotReadableException. The DTO is never created, so no constraint is evaluated.