Spring Boot & Spring Cloud

Validation and Error Handling in Spring Boot 3: Bean Validation and Problem Details

Intermediate6 min readUpdated

You will be able to reject bad input before it reaches business logic and return errors clients can act on: apply Jakarta Bean Validation constraints to records and method parameters, write custom constraints, centralise exception handling in a @RestControllerAdvice, and emit standard application/problem+json responses without leaking internals.

What you will learn

  • Apply Jakarta Bean Validation constraints to request DTOs and controller parameters and know which exception each produces
  • Write a custom constraint with a validator class and use validation groups
  • Enable Spring's built-in ProblemDetail support and understand what it covers
  • Centralise domain and validation errors in a @RestControllerAdvice that produces RFC 9457 problem details
  • Avoid leaking stack traces, entity structure and framework messages in error responses

An API is judged as much by how it fails as by how it succeeds. Clients need to know whether they sent something wrong, whether the resource exists, whether retrying will help, and which field to fix. Spring Boot 3 gives you the pieces to answer those questions consistently: Jakarta Bean Validation for declaring what valid input looks like, exception handlers for mapping failures to responses, and the ProblemDetail type from Spring Framework 6 for a standard error body. This page assembles them into one approach you can apply to every endpoint.

Declaring constraints

Add spring-boot-starter-validation, which brings Hibernate Validator, the reference implementation of Jakarta Bean Validation 3. The API lives in jakarta.validation; if you see javax.validation imports, you are reading pre-Boot 3 material.

Constraints are annotations on fields, record components, parameters and return values:

import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.util.List;

public record CreateCustomerRequest(
        @NotBlank @Size(max = 100) String name,
        @NotBlank @Email String email,
        @Pattern(regexp = "^\\+?[0-9 ]{6,20}$", message = "must be a phone number with digits and spaces")
        String phone,
        @NotNull @Past LocalDate dateOfBirth,
        @Valid @NotEmpty List<AddressRequest> addresses) {   // @Valid cascades into each element

    public record AddressRequest(
            @NotBlank String street,
            @NotBlank String city,
            @NotBlank @Size(min = 2, max = 2) String countryCode) {}
}

The frequently used built-ins are @NotNull, @NotBlank (non-null and at least one non-whitespace character), @NotEmpty (non-null and non-empty, for collections and strings), @Size, @Min/@Max, @Positive/@PositiveOrZero, @DecimalMin/@DecimalMax, @Digits, @Past/@Future (and their OrPresent variants), @Email and @Pattern. Hibernate Validator adds a few such as @URL and @Length, at the cost of tying you to that implementation.

Two things surprise people. Constraints do not cascade unless you say so: a List<AddressRequest> is only checked for @NotEmpty until you add @Valid. And @NotNull on a primitive int is meaningless; primitives are never null, so a missing JSON field silently becomes zero. Use a boxed Integer with @NotNull when absence must be an error.

For regular expressions in @Pattern, remember that the whole value must match; you can try patterns against sample inputs in the regex tester before committing them.

Triggering validation in controllers

Spring MVC runs validation at three points, each raising a different exception:

Where the constraint sitsTriggerExceptionDefault status
@RequestBody object with @ValidArgument resolutionMethodArgumentNotValidException400
@RequestParam, @PathVariable, @RequestHeader (Spring 6.1+)Built-in method validationHandlerMethodValidationException400
Any method of a class annotated @Validated (services, older controllers)AOP proxyConstraintViolationException500 unless handled
@RestController
@RequestMapping("/api/customers")
class CustomerController {

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    CustomerResponse create(@Valid @RequestBody CreateCustomerRequest request) {
        return CustomerResponse.from(customers.register(request));
    }

    @GetMapping
    Page<CustomerResponse> search(@RequestParam @Size(min = 2) String q,
                                  @RequestParam(defaultValue = "20") @Max(100) int size) {
        return customers.search(q, size).map(CustomerResponse::from);
    }
}

The third row is worth understanding. Before Spring Framework 6.1, constraints on simple parameters were ignored unless the controller carried @Validated, which wrapped it in a proxy; the resulting ConstraintViolationException was not handled by Spring MVC and produced a 500. Since 6.1 the framework validates these parameters itself when a provider is present, and the HandlerMethodValidationException is treated as a 400. If you still annotate controllers with @Validated, remove it so that the two mechanisms do not both run.

@Validated remains the tool for services: annotate the class, put constraints on the method parameters, and callers that pass bad data get a ConstraintViolationException regardless of whether the call came from HTTP, a scheduler or a message listener.

Custom constraints and groups

When a rule is reusable and purely about the value (an IBAN, an internal product code, a strong password), write a constraint rather than repeating checks in services:

@Documented
@Constraint(validatedBy = SkuValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
public @interface Sku {
    String message() default "must be a SKU such as ABC-12345";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class SkuValidator implements ConstraintValidator<Sku, String> {
    private static final Pattern FORMAT = Pattern.compile("[A-Z]{3}-\\d{5}");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value == null || FORMAT.matcher(value).matches();   // null is @NotNull's job
    }
}

Return true for null so that optionality stays a separate decision made with @NotNull. Validators are Spring beans when Boot's LocalValidatorFactoryBean is in use, so they can inject a repository to check, say, that an email is not already registered; keep such checks cheap, because they run on every validation of the object, and handle the race condition at the database with a unique constraint anyway.

Groups let one record carry different rules for different operations. Declare marker interfaces (OnCreate, OnUpdate), attach them with @NotNull(groups = OnUpdate.class), and validate with @Validated(OnUpdate.class) on the controller parameter. Groups are powerful and easy to overuse; separate request records per operation are often clearer.

Class-level constraints (annotation on the record, validator receiving the whole object) express cross-field rules such as "end date after start date". Put genuinely business-level rules, the ones that need other aggregates or a transaction, in the service, and throw a domain exception instead.

Standard error bodies with ProblemDetail

RFC 9457 (which obsoletes RFC 7807) defines a JSON shape for errors that most API tooling already understands:

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Request validation failed",
  "status": 400,
  "detail": "2 fields are invalid",
  "instance": "/api/customers",
  "errors": [
    { "field": "email", "message": "must be a well-formed email address" },
    { "field": "addresses[0].countryCode", "message": "size must be between 2 and 2" }
  ]
}

Spring Framework 6 models this as org.springframework.http.ProblemDetail, written with the media type application/problem+json. Boot switches the framework's own exception handling to this format with one property:

spring.mvc.problemdetails.enabled=true

That registers a ResponseEntityExceptionHandler covering the exceptions Spring MVC raises itself: unreadable bodies, unsupported media types, missing parameters, MethodArgumentNotValidException, HandlerMethodValidationException, NoResourceFoundException and others. It does not know about your domain exceptions, and its validation response lists no field errors, so in practice you extend it.

A single @RestControllerAdvice

Centralise the mapping in one class so every controller fails the same way:

@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    private static final URI VALIDATION_TYPE = URI.create("https://api.example.com/problems/validation-error");

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        List<Map<String, String>> errors = ex.getBindingResult().getFieldErrors().stream()
                .map(fe -> Map.of("field", fe.getField(),
                                  "message", Objects.requireNonNullElse(fe.getDefaultMessage(), "invalid")))
                .toList();
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(status,
                errors.size() + " field(s) are invalid");
        problem.setType(VALIDATION_TYPE);
        problem.setTitle("Request validation failed");
        problem.setProperty("errors", errors);
        return handleExceptionInternal(ex, problem, headers, status, request);
    }

    @ExceptionHandler(CustomerNotFoundException.class)
    ProblemDetail notFound(CustomerNotFoundException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND,
                "No customer with id " + ex.customerId());
        problem.setTitle("Customer not found");
        return problem;
    }

    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)
    ProblemDetail conflict(ObjectOptimisticLockingFailureException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,
                "The resource was modified by another request; reload and retry");
        problem.setTitle("Concurrent modification");
        return problem;
    }

    @ExceptionHandler(Exception.class)
    ProblemDetail unexpected(Exception ex, HttpServletRequest request) {
        log.error("Unhandled exception for {} {}", request.getMethod(), request.getRequestURI(), ex);
        ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        problem.setTitle("Unexpected error");
        problem.setDetail("The request could not be processed. Reference: " + MDC.get("traceId"));
        return problem;
    }
}

Returning a ProblemDetail from an @ExceptionHandler is enough for Spring to set the status from it and the content type to application/problem+json. setProperty adds extension members (errors above) that serialise at the top level of the JSON, as the RFC intends. The catch-all handler logs the real exception with its stack trace and returns only a reference the caller can quote to support; a trace or correlation id from your tracing setup is ideal.

Domain exceptions can also extend Spring's ErrorResponseException, which carries a ProblemDetail and needs no handler at all. That is convenient for small services; the advice class scales better once you want to vary the response by exception type or add logging.

Order matters when several handlers could match: Spring picks the closest exception type, so CustomerNotFoundException beats Exception. If two advice classes exist, @Order decides which is consulted first.

Boot's own /error fallback (the BasicErrorController) still handles anything that escapes MVC, such as failures inside a filter. Its output is controlled by server.error.include-message, include-binding-errors, include-stacktrace and include-exception, all of which should stay at their never defaults in production.

Messages and internationalisation

Constraint messages are resolved through a MessageSource. Put them in ValidationMessages.properties (the Bean Validation convention, on the classpath root) or, from Boot 2.6 onwards, in the application's messages.properties, because Boot wires its MessageSource into the validator:

customer.email.invalid=Enter a valid email address such as [email protected]

Then reference it with @Email(message = "{customer.email.invalid}"). Locale-specific files (messages_fr.properties) are chosen from the request's Accept-Language header. Whether to translate API error messages at all is a product decision; many APIs return machine-readable codes and let the client localise.

Common mistakes

Forgetting @Valid on the body. The constraints are declared, the starter is present, and nothing happens. Validation of a @RequestBody is opt-in per parameter.

Validating too late. Constraints on entities (@NotBlank on a JPA field) run at flush time, inside the transaction, and surface as a TransactionSystemException wrapping a ConstraintViolationException. Validate at the API boundary on request records and treat entity constraints as a second line of defence.

Copying ex.getMessage() into the response. DataIntegrityViolationException messages contain SQL and constraint names; HttpMessageNotReadableException messages contain class names and Jackson internals. Write the detail yourself.

Returning a different error shape per controller. Two handlers, one producing { "error": ... } and another { "message": ... }, force every client to special-case. One advice class, one shape.

Throwing ResponseStatusException everywhere. It is fine for a quick 404, but its message becomes the response reason, its bodies are inconsistent with your problem details, and it scatters HTTP knowledge through services. Throw domain exceptions and map them once.

Enabling include-stacktrace=always "just for staging". Staging configuration has a way of becoming production configuration. Log traces; never return them.

Key takeaways

  • Declare validity with Jakarta Bean Validation constraints on request records; @Valid on the @RequestBody triggers them, @Valid on nested fields cascades.
  • Since Spring Framework 6.1, constraints on @RequestParam and @PathVariable are enforced without @Validated and produce HandlerMethodValidationException.
  • Custom constraints handle reusable format rules; business rules that need other data belong in services as domain exceptions.
  • spring.mvc.problemdetails.enabled=true plus a @RestControllerAdvice extending ResponseEntityExceptionHandler gives every failure the same RFC 9457 shape.
  • Add field-level errors as an extension member, keep detail human-readable, and never copy raw exception messages or stack traces into a response.
  • Log unexpected exceptions server-side with a correlation id and return that id to the client.

Sources and further reading

Frequently asked questions

What is the difference between @Valid and @Validated?
@Valid is the Jakarta Bean Validation annotation: on a controller parameter it validates the object and triggers cascading into nested objects marked @Valid. @Validated is Spring's annotation: it accepts validation groups, and on a class it enables method-level validation of parameters and return values through a proxy. Use @Valid on request bodies and @Validated when you need groups or want to validate a service's method arguments.
Why do constraints on @RequestParam or @PathVariable do nothing?
Before Spring Framework 6.1, constraints on simple parameters were only enforced if the controller class was annotated with @Validated, which created a proxy and raised ConstraintViolationException. Since 6.1 Spring MVC validates them natively whenever a Bean Validation provider is present, and raises HandlerMethodValidationException instead. Check the framework version and make sure spring-boot-starter-validation is on the classpath.
Should I return 400 or 422 for validation failures?
Both are defensible. 400 Bad Request is what Spring's default handling uses for MethodArgumentNotValidException and is understood by every client. 422 Unprocessable Content is more precise when the JSON is well-formed but violates business rules. Choose one, document it in the API, and apply it consistently; do not mix them for the same kind of failure.
How do I stop Spring Boot from exposing exception messages and stack traces?
Boot's default error response already omits the message and trace unless server.error.include-message or server.error.include-stacktrace are set to always. Keep them at never in production, and make your @RestControllerAdvice map exceptions to hand-written detail strings rather than copying exception.getMessage(), which for persistence and framework errors often contains SQL, class names or file paths.