Articles Spring

Spring Boot validation error response with ProblemDetail

To get a useful validation error response in Spring Boot, put Bean Validation annotations on a request record, mark the controller parameter with @Valid, and add one @RestControllerAdvice that extends ResponseEntityExceptionHandler and returns a ProblemDetail with a list of field errors. Out of the box Spring Boot answers a failed validation with a 400 that does not say which field was wrong, so the advice is the part that matters.

Every response below was captured from a running application on Spring Boot 4.2.0 (Spring Framework 7.1.0) and compared with Boot 4.1.1 and 3.5.15. The differences are called out where they exist.

How do you validate a request body in Spring Boot?

Validation is not part of the web starter. Add it explicitly:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

It brings in Hibernate Validator, the reference implementation of Jakarta Validation. The constraints go on the components of a record, and @Valid on the parameter tells Spring MVC to check it before the method runs:

public record CreateUserRequest(
        @NotBlank @Email String email,
        @NotBlank @Size(min = 2, max = 50) String displayName,
        @Min(18) int age) {}

@RestController
public class UserController {

    @PostMapping("/users")
    @ResponseStatus(HttpStatus.CREATED)
    CreateUserRequest create(@Valid @RequestBody CreateUserRequest request) {
        return request;
    }
}

Without @Valid the annotations on the record are ignored and the invalid object reaches your code.

What does Spring Boot return by default when validation fails?

Send a body that breaks all three rules:

{"email": "not-an-email", "displayName": "A", "age": 15}

The answer is 400 with Content-Type: application/json and this body:

{
  "timestamp": "2026-11-28T23:02:20.155Z",
  "status": 400,
  "error": "Bad Request",
  "path": "/users"
}

The three violations are written to the application log as a MethodArgumentNotValidException warning, but the client learns nothing about them. This is Spring Boot’s generic /error response, the same shape you get for any unhandled error.

What does spring.mvc.problemdetails.enabled change?

spring.mvc.problemdetails.enabled=true

The property is false by default, in Boot 4 as in Boot 3 (application properties reference). With it switched on, the same request returns Content-Type: application/problem+json:

{
  "detail": "Invalid request content.",
  "status": 400,
  "title": "Bad Request"
}

The format is now standard, and Spring MVC’s own exceptions (malformed JSON, a wrong parameter type, a missing parameter) use it too. The field errors are still missing: which details to expose is left to the application.

What is ProblemDetail (RFC 9457)?

RFC 9457, “Problem Details for HTTP APIs”, defines one JSON shape for errors. It obsoletes RFC 7807 and keeps the same media type, application/problem+json. The standard members are:

  • type: a URI that identifies the kind of problem. When it is absent, it means about:blank.
  • title: a short summary that stays the same for every occurrence of that type.
  • status: the HTTP status code.
  • detail: an explanation of this particular occurrence.
  • instance: a URI that identifies this particular occurrence.

Anything else is an extension member, which is where field errors belong. In Spring the body is org.springframework.http.ProblemDetail, and setProperty adds extension members that Jackson writes as top-level JSON properties.

The output differs between versions. On Boot 3.5.15 the same response was:

{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "Invalid request content.",
  "instance": "/users"
}

Boot 4.1.1 dropped the default type but still filled instance with the request path. Boot 4.2.0 writes neither: the Spring Framework reference states that as of 7.1 instance is no longer set to the path, since the RFC means it to identify one occurrence. Clients that read instance or compare type with about:blank need a look before you upgrade.

How do you add field errors to the ProblemDetail response?

ResponseEntityExceptionHandler already handles every Spring MVC exception and has one protected method per exception type. Override the one for @Valid failures:

@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    record FieldProblem(String field, String message) {}

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        List<FieldProblem> errors = ex.getBindingResult().getFieldErrors().stream()
                .map(e -> new FieldProblem(e.getField(), e.getDefaultMessage()))
                .toList();
        ProblemDetail body = ex.getBody();
        body.setProperty("errors", errors);
        return handleExceptionInternal(ex, body, headers, status, request);
    }
}

The response to the invalid request becomes:

{
  "detail": "Invalid request content.",
  "status": 400,
  "title": "Bad Request",
  "errors": [
    {"field": "age", "message": "must be greater than or equal to 18"},
    {"field": "displayName", "message": "size must be between 2 and 50"},
    {"field": "email", "message": "must be a well-formed email address"}
  ]
}

Two things to know. Once this advice exists you no longer need the property, because the base class produces problem details by itself. And the order of errors is not guaranteed: the run on Boot 4.1.1 listed email first. Sort the list if clients or tests depend on the order.

How do you validate @RequestParam and @PathVariable?

Put the constraints directly on the parameters. Since Spring Framework 6.1 (Spring Boot 3.2) this works with no extra annotation on the class:

@GetMapping("/users")
List<String> list(@RequestParam @Min(0) int page,
                  @RequestParam @Min(1) @Max(100) int size) {
    return List.of();
}

A violation here raises HandlerMethodValidationException, not MethodArgumentNotValidException, so the advice needs a second override:

@Override
protected ResponseEntity<Object> handleHandlerMethodValidationException(
        HandlerMethodValidationException ex, HttpHeaders headers,
        HttpStatusCode status, WebRequest request) {
    List<FieldProblem> errors = ex.getParameterValidationResults().stream()
            .flatMap(result -> result.getResolvableErrors().stream()
                    .map(e -> new FieldProblem(
                            result.getMethodParameter().getParameterName(),
                            e.getDefaultMessage())))
            .toList();
    ProblemDetail body = ex.getBody();
    body.setProperty("errors", errors);
    return handleExceptionInternal(ex, body, headers, status, request);
}

GET /users?page=-1&size=500 then returns 400 with:

{
  "detail": "Validation failure",
  "status": 400,
  "title": "Bad Request",
  "errors": [
    {"field": "page", "message": "must be greater than or equal to 0"},
    {"field": "size", "message": "must be less than or equal to 100"}
  ]
}

Older tutorials tell you to annotate the controller class with @Validated. Do not: with that annotation validation runs through an AOP proxy and throws jakarta.validation.ConstraintViolationException, which Spring MVC does not map to a status. The same request against a controller with class-level @Validated returned a 500 on both Boot 4.2.0 and 3.5.15. The validation section of the reference says to remove the annotation to get the built-in behaviour. It also notes that a constraint next to @Valid on a body parameter, such as @NotNull, switches that method to method validation, which is why an API should handle both exceptions.

How do you return ProblemDetail for your own exceptions?

For a domain error such as “not found” there are two options. The exception can carry its own response by extending ErrorResponseException:

public class OrderNotFoundException extends ErrorResponseException {
    public OrderNotFoundException(long id) {
        super(HttpStatus.NOT_FOUND);
        setTitle("Order not found");
        setDetail("Order " + id + " does not exist");
    }
}

Or the exception stays a plain RuntimeException with no web dependency, and the advice translates it:

@ExceptionHandler(UserNotFoundException.class)
ProblemDetail handleUserNotFound(UserNotFoundException ex) {
    ProblemDetail body = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    body.setTitle("User not found");
    body.setProperty("userId", ex.id());
    return body;
}

GET /users/42 returns 404 with application/problem+json:

{
  "detail": "User 42 does not exist",
  "status": 404,
  "title": "User not found",
  "userId": 42
}

The second form keeps HTTP out of the domain layer. Without that handler the same exception produced a plain 500.

What should an error response never contain?

Stack traces, SQL statements, exception class names, file paths and library versions help an attacker and are useless to a client. Build detail from text you wrote, never from getMessage() of an exception you did not throw, and answer everything unexpected with a generic 500 while the full exception goes to the log. Rejected values deserve the same care: echoing a submitted password back in an error is a leak.

Summary

  • Add spring-boot-starter-validation, annotate the request record, put @Valid on the parameter.
  • The default response is a bare 400. spring.mvc.problemdetails.enabled=true changes the format to RFC 9457 but adds no field errors.
  • One @RestControllerAdvice extending ResponseEntityExceptionHandler adds an errors list for both MethodArgumentNotValidException and HandlerMethodValidationException.
  • Constraints on @RequestParam and @PathVariable work without class-level @Validated, and adding it turns a 400 into a 500.
  • Spring Framework 7 omits the default type, and 7.1 stops filling instance with the request path.
  • Map domain exceptions to ProblemDetail in the same advice and keep internals out of the body.