Sub topic 6
Returning structured error responses
This chapter assumes you can write a Spring MVC controller, you know what a Java record is, and you have already put @Valid on a @RequestBody parameter. You also need the validation starter on the classpath. Here you will turn validation failures into consistent JSON error bodies that clients can parse.
Why the default response is not enough
When @Valid fails on a request body, Spring throws MethodArgumentNotValidException. With no handler of your own, Spring Boot answers with a 400 status. The default body depends on your Boot version and configuration, and it does not always list the failing fields in a form that clients can rely on.
A client that submits a form wants to know which field failed and why. It wants the same shape for every error in your API. Three things make that possible:
- A single place that catches validation exceptions, so no controller repeats the logic.
- A standard error format, so every error looks the same.
- A stable mapping from field name to message, so the client can attach each message to an input.
Spring provides each of them. @RestControllerAdvice is the central place. ProblemDetail is the standard format. BindingResult supplies the field errors.
The pieces
@RestControllerAdvice
A class annotated with @RestControllerAdvice applies its @ExceptionHandler methods to every controller in the application. The return value is written to the response body, as in a @RestController. You can narrow its scope with attributes such as basePackages or assignableTypes if you need different handling in different parts of the application.
ProblemDetail
ProblemDetail is a Spring class (since Spring Framework 6) that models the "Problem Details for HTTP APIs" format from RFC 9457, which replaced RFC 7807. It has these standard members:
| Member | Meaning |
|---|---|
| `type` | A URI that identifies the kind of problem. Defaults to `about:blank`. |
| `title` | A short summary. Derived from the status when you do not set it. |
| `status` | The HTTP status code. |
| `detail` | A human-readable explanation of this occurrence. |
| `instance` | A URI for this specific occurrence. Spring sets it to the request path. |
You can add custom members with setProperty. They appear at the top level of the JSON object. Responses are served with the media type application/problem+json.
BindingResult
MethodArgumentNotValidException carries a BindingResult. Its getFieldErrors() method returns one FieldError per violated constraint. Each has getField(), which is the property name, and getDefaultMessage(), which is the resolved message text. getGlobalErrors() returns errors that belong to the object as a whole, such as those from a class-level constraint.
The flow
The diagram shows what happens from request to response.
Validation runs after the body is deserialized, so the controller method never starts when a constraint fails. If the JSON itself is malformed, a different exception occurs before validation. See the pitfalls below.
Building the handler
This is the handler from the plan. It builds a ProblemDetail with status 400, then adds an errors property that maps each field to one 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;
}
}A few details matter here.
ProblemDetail.forStatusAndDetailsets the status and detail. The handler returns the object directly, and Spring usesstatusto set the HTTP status code of the response.LinkedHashMapkeeps the fields in the order the binder reported them, so the output is stable.putIfAbsentkeeps only the first message per field. A field with@NotBlankand@Emailcan fail both at once, and a map cannot hold two values under one key. The error order for a single field is not guaranteed, so the message you keep may vary between runs.
A sample exchange
Assume the DTO from the earlier chapter:
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@NotNull @Min(18) Integer age) {
}A request with a blank name, a malformed email and an age of 12:
{ "name": "", "email": "not-an-email", "age": 12 }A typical response is:
{
"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"
}
}The exact message wording comes from Hibernate Validator and depends on the locale. A later chapter on messages shows how to replace it.
Keeping every field message
Dropping all but the first message loses information. If clients should see every problem, collect a list per field instead.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
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 AllMessagesExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleInvalidBody(MethodArgumentNotValidException ex) {
ProblemDetail problem =
ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
Map<String, List<String>> errors = new LinkedHashMap<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.computeIfAbsent(error.getField(), key -> new ArrayList<>())
.add(error.getDefaultMessage());
}
problem.setProperty("errors", errors);
return problem;
}
}Choose between the two shapes on the basis of the client. A map of strings is easy to bind to a form. A map of lists is complete but harder to render. Do not register both classes in the same application with the same exception type, because Spring would have two competing handlers and could not choose reliably between them.
Handling global errors
Constraints placed on the class, rather than on a field, produce global errors. They do not appear in getFieldErrors(). If you use class-level rules, add them to the response:
import java.util.List;
import org.springframework.validation.ObjectError;
List<String> globalErrors = ex.getBindingResult().getGlobalErrors().stream()
.map(ObjectError::getDefaultMessage)
.toList();
if (!globalErrors.isEmpty()) {
problem.setProperty("globalErrors", globalErrors);
}Place this inside the handler method, before it returns. Without it, a failed class-level check returns "Validation failed" with an empty errors object, which tells the client nothing.
Letting Spring Boot do part of the work
Spring MVC already knows ProblemDetail. Two settings are relevant:
spring.mvc.problemdetails.enabled=trueturns on a built-inResponseEntityExceptionHandlerthat renders standard Spring MVC exceptions, includingMethodArgumentNotValidException, asProblemDetailresponses.- Extending
ResponseEntityExceptionHandlerin your own advice class gives you the same behavior and lets you override single methods, such ashandleMethodArgumentNotValid.
The built-in rendering gives status 400 and a generic detail such as "Invalid request content". It does not include the per-field errors map. If you want that, you need to add it yourself. A common way is to extend ResponseEntityExceptionHandler and override the method.
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@RestControllerAdvice
public class BaseApiExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
ProblemDetail problem = ex.getBody();
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError error : ex.getBindingResult().getFieldErrors()) {
errors.putIfAbsent(error.getField(), error.getDefaultMessage());
}
problem.setProperty("errors", errors);
return handleExceptionInternal(ex, problem, headers, status, request);
}
}This approach also covers other framework exceptions, such as unsupported media types, with the same ProblemDetail format. That consistency is the main reason to prefer it in a larger API. The trade-off is a dependency on the base class and its method signatures, which can change between Spring versions. The standalone handler is simpler and has no such coupling, but you must handle the other exception types yourself.
Common pitfalls
- Two handlers for one exception. Only one
@ExceptionHandlermethod should match a given exception type in the application. Otherwise Spring reports an ambiguity or uses an unexpected one. - Malformed JSON. A body that is not valid JSON, or has a value of the wrong type such as a string where a number is expected, throws
HttpMessageNotReadableExceptionbefore validation starts. Your validation handler never sees it. Handle it separately or use theResponseEntityExceptionHandlerapproach. - Exposing internals. Do not return
ex.getMessage()for validation errors. It contains class and method details. Build the response fromgetFieldErrors(), as shown. - Nested field names. Errors in nested objects use dotted paths such as
address.city, and collection items use indexes such aslines[0].sku. Clients should expect these keys. - Wrong exception for parameters. Constraints on path variables and query parameters do not throw
MethodArgumentNotValidExceptionin the way described here. A later chapter covers that exception and its handler.
Verifying the behavior
Run the application and send an invalid request:
curl -i -X POST http://localhost:8080/users \
-H "Content-Type: application/json" \
-d '{"name":"","email":"bad","age":12}'Check three things in the output: the status line is 400, the Content-Type is application/problem+json, and the errors object has one key per invalid field. If you get an HTML error page or a different JSON shape, your advice class is not being picked up. Confirm that it sits in a package scanned by your @SpringBootApplication class.
Exercise
A DTO field is annotated with both @NotBlank and @Email, and the client sends an empty string. The handler uses errors.putIfAbsent(error.getField(), error.getDefaultMessage()). How many messages for that field appear in the response, and how would you change the handler to return all of them?
Show answer
Only one message appears, because putIfAbsent ignores later values for the same key, even though both constraints may have failed. To return all of them, change the map to Map<String, List<String>> and use errors.computeIfAbsent(error.getField(), key -> new ArrayList<>()).add(error.getDefaultMessage()).
Exercise
A client sends {"name": "Ann", "email": "[email protected]", "age": "abc"} to the endpoint. Does your MethodArgumentNotValidException handler run? Explain.
Show answer
No. The value "abc" cannot be converted to Integer, so Jackson fails while reading the body and Spring throws HttpMessageNotReadableException. Validation never starts, so the handler for MethodArgumentNotValidException is not called. You need a separate handler for the other exception, or a class that extends ResponseEntityExceptionHandler.