Sub topic 6
Returning structured error responses
This chapter assumes you can write a Spring MVC controller, and that you have a request DTO with constraint annotations and @Valid on the @RequestBody parameter. It covers what the client receives when validation fails, and how to make that response consistent.
The default response is not enough
If validation fails, Spring throws MethodArgumentNotValidException before your controller method runs. With no handler, the client gets a 400 status. The body is either empty or a generic message, depending on your configuration. The client can't tell which field was wrong or why.
A structured response fixes this. It uses a stable JSON shape, the right status code, and one message per invalid field. Spring's ProblemDetail class models the RFC 9457 "problem details" format, so you don't need to design your own error type.
Handling invalid request bodies
A @RestControllerAdvice class applies its @ExceptionHandler methods to every controller. This handler turns the exception into a ProblemDetail and adds a map from field name to message.
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
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalidBody(MethodArgumentNotValidException ex) {
ProblemDetail 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;
}
}getBindingResult().getFieldErrors() returns one FieldError for each violated constraint. A field can violate several constraints at once. For example, an empty name may break both @NotBlank and a size rule. putIfAbsent keeps the first message for each field, so the map stays one entry per field.
Posting {"name": "", "email": "nope", "age": 12} to /users now returns this body with the application/problem+json content type. Message wording comes from Hibernate Validator's defaults, and the order of the errors entries may vary.
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failed",
"instance": "/users",
"errors": {
"name": "must not be blank",
"email": "must be a well-formed email address",
"age": "must be greater than or equal to 18"
}
}Handling invalid parameters
Constraints on path variables and query parameters fail differently. When the controller has class-level @Validated, a violation raises jakarta.validation.ConstraintViolationException. Your first handler does not catch it, so the client sees a 500 error. Add a second handler to the same class:
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
@ExceptionHandler(ConstraintViolationException.class)
public ProblemDetail handleInvalidParameters(ConstraintViolationException ex) {
ProblemDetail problem =
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, String> errors = new LinkedHashMap<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.put(violation.getPropertyPath().toString(), violation.getMessage());
}
problem.setProperty("errors", errors);
return problem;
}Add the imports above to the existing ApiExceptionHandler file. The property path looks like find.id, which is the method name followed by the parameter name. The parameter name appears only if the code is compiled with the -parameters flag. Spring Boot's Maven and Gradle plugins set it by default. Otherwise the path shows arg0.
Common mistakes
- Missing the second handler, so parameter violations return 500 instead of 400.
- Returning
ex.getMessage()directly. It exposes class names and internal paths, and it isn't meant for clients. - Using
Collectors.toMapon field errors. It throwsIllegalStateExceptionwhen a field has two violations. - Changing the
errorsshape between handlers, so clients need two parsers.
Exercise
A client sends GET /orders/0 to a controller that has @Validated and @PathVariable @Min(1) long id. Which exception is thrown, and what must your advice class contain so the client gets a 400?
Show answer
A ConstraintViolationException is thrown. The advice needs an @ExceptionHandler(ConstraintViolationException.class) method that returns a 400 ProblemDetail. The MethodArgumentNotValidException handler does not cover this case.