Sub topic 2
What Happens When Validation Fails
Assume you know Java records, Spring MVC controllers, Maven or Gradle, and basic HTTP status codes. This chapter focuses on the exceptions Spring raises and how to return useful JSON errors.
Validation failure flow
When @Valid checks a request body, Spring validates the object before entering the controller method. If a field violates a constraint, Spring raises MethodArgumentNotValidException. The method body does not run.
When @Validated checks a path variable or query parameter, Spring raises ConstraintViolationException instead.
| Input | Typical exception | Response |
|---|---|---|
| `@Valid @RequestBody` | `MethodArgumentNotValidException` | 400 Bad Request |
| `@PathVariable` or `@RequestParam` with `@Validated` | `ConstraintViolationException` | 400 Bad Request |
Returning structured error responses
A @RestControllerAdvice class handles exceptions across controllers. ProblemDetail is Spring’s standard container for an HTTP problem response. Add field errors as a custom property.
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail handleBody(MethodArgumentNotValidException ex) {
var problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.putIfAbsent(error.getField(), error.getDefaultMessage());
}
problem.setProperty("errors", errors);
return problem;
}
}The response includes status 400, a general detail, and an errors object such as {"email":"must be a well-formed email address"}. Add a second handler for ConstraintViolationException when parameters are validated.
Validating path variables and query parameters
Put @Validated on the controller, then annotate the parameters.
import jakarta.validation.constraints.Min;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@Validated
class OrderController {
@GetMapping("/orders/{id}")
String find(@PathVariable @Min(1) long id) {
return "order " + id;
}
}An ID of 0 produces a validation exception before find runs. Handle that exception consistently in the advice class.
Exercise
Which exception should an advice class handle for an invalid @RequestBody?
Show answer
MethodArgumentNotValidException.