Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 119 ยท Spring Boot

Validation and Error Handling

Validate Spring Boot requests with Jakarta Bean Validation (@Valid, @NotBlank, @Size, custom constraints) and return consistent ProblemDetail errors from @RestControllerAdvice.

An API is only as robust as its handling of bad input. Clients send empty names, negative quantities, ISBNs with typos and JSON that doesn't parse, and sooner or later your own code throws an exception nobody expected. A good API rejects bad input early, reports every problem in one response, uses the right status code, and returns errors in one consistent format that never leaks internal details.

Spring Boot gives you two tools for this. Jakarta Bean Validation lets you declare rules on your input records with annotations like @NotBlank and @Size, and @Valid makes Spring check them before your controller method runs. @RestControllerAdvice with @ExceptionHandler turns exceptions into responses in one central place, using the standard problem details format (RFC 9457) through Spring's ProblemDetail class. In this lesson you will use both, and run small re-implementations of each mechanism so you can see exactly how they work. You should know Building REST APIs with Spring Boot first.

Declaring constraints

Add the validation starter, which brings Hibernate Validator, the reference implementation of Jakarta Bean Validation:

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

Then put constraint annotations (from jakarta.validation.constraints) on the fields or record components of your input types:

Java
import jakarta.validation.constraints.*;

public record NewUser(
        @NotBlank @Size(max = 50) String name,
        @NotBlank @Email String email,
        @NotNull @Min(13) @Max(130) Integer age,
        @Size(min = 8, max = 72) String password,
        @Pattern(regexp = "[A-Z]{2}") String country,
        @Past LocalDate birthday) {
}

The built-in constraints you will use most:

Constraint Valid when
@NotNull Not null
@NotEmpty Not null and not empty (strings, collections, maps, arrays)
@NotBlank Not null and contains at least one non-whitespace character (strings)
@Size(min, max) Length or size within bounds
@Min, @Max, @Positive, @PositiveOrZero, @DecimalMin Number within bounds
@Email, @Pattern(regexp) Matches an email shape, or a regular expression (the whole string)
@Past, @PastOrPresent, @Future Date/time relative to now
@AssertTrue A boolean (often a method like isEndAfterStart()) is true

null is valid for every constraint except @NotNull, @NotEmpty and @NotBlank. @Size(min = 8) String password accepts a missing password; @Email accepts a missing email. This is by design (each constraint checks one thing), so combine them: @NotBlank @Email. It's also why input records use Integer instead of int: a missing int silently becomes 0 and passes @Min(0).

Here is a small validation engine, written with our own annotations of the same names, that walks a record's components and collects every violation. Look at the first user: four problems are reported at once. Then look at the second: password and country are missing, yet valid, because of the null rule above.

Java How Bean Validation checks a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

@Valid on request bodies

Constraints do nothing until something triggers validation. In a controller, that something is @Valid (from jakarta.validation) or Spring's @Validated on the parameter:

Java
@PostMapping("/api/users")
public ResponseEntity<User> register(@Valid @RequestBody NewUser input) {
    User user = users.register(input);         // runs only if input is valid
    return ResponseEntity.created(URI.create("/api/users/" + user.id())).body(user);
}

If any constraint fails, Spring throws MethodArgumentNotValidException before your method runs and, by default, answers 400 Bad Request. The exception carries a BindingResult with every field error: the field name, the rejected value and the message.

Parameters can be validated too. Put constraints directly on @PathVariable and @RequestParam parameters:

Java
@GetMapping("/api/books")
public List<Book> list(@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size,
                       @RequestParam(defaultValue = "0") @PositiveOrZero int page) { ... }

Since Spring Framework 6.1, Spring MVC applies this method validation by itself when it sees constraint annotations on parameters, and reports failures as HandlerMethodValidationException (also 400). Older code put @Validated on the controller class to get the same effect through a proxy; that still works but is no longer required for controllers.

Nested objects and lists

Validation does not descend into nested objects unless you ask for it with @Valid on the field (this is called cascading). For lists, put @Valid on the element type:

Java
public record NewOrder(
        @NotBlank String customerId,
        @Valid @NotNull Address shippingAddress,
        @NotEmpty List<@Valid OrderLine> lines) {}

public record OrderLine(@NotBlank String isbn, @Positive int quantity) {}

Violations in nested objects get paths such as shippingAddress.city or lines[1].quantity, so clients can highlight the exact field.

Custom constraints

When the rule is specific to your domain (a valid ISBN, a SKU format, an allowed currency), write your own constraint: an annotation marked with @Constraint, plus a ConstraintValidator that does the check.

Java
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.RECORD_COMPONENT, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IsbnValidator.class)
public @interface Isbn {
    String message() default "must be a valid ISBN-13";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class IsbnValidator implements ConstraintValidator<Isbn, String> {
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.isBlank()) return true;   // leave these to @NotNull/@NotBlank
        String digits = value.replace("-", "");
        if (!digits.matches("\\d{13}")) return false;
        int sum = 0;
        for (int i = 0; i < 13; i++) sum += (digits.charAt(i) - '0') * (i % 2 == 0 ? 1 : 3);
        return sum % 10 == 0;
    }
}

The three attributes message, groups and payload are required by the specification. Validators are created by Spring, so they can even have injected dependencies (for example a repository to check uniqueness, although such checks are better done in the service, inside the transaction that saves the data).

The next program rebuilds this design: a @Constraint(validatedBy = ...) meta-annotation, a validator interface, cascading into a nested record and into list elements, and property paths in the result.

Java Custom constraints and cascading validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The empty ISBN in the last line produces only "must not be blank". The ISBN validator deliberately returns true for null and blank values and leaves those to @NotBlank, so the client gets one clear message instead of two. Follow the same rule in your own validators: check one thing, and let the standard constraints handle "missing".

Central error handling with @RestControllerAdvice

Validation is one source of errors. Others are "not found", conflicts, permission problems and plain bugs. Handling them with try/catch in every controller method would bury the logic. Instead, let exceptions propagate and translate them in one place.

An @ExceptionHandler method handles exceptions of the given type thrown by controller methods. Inside a controller it applies to that controller only; inside a class annotated with @RestControllerAdvice it applies to all controllers:

Java
@RestControllerAdvice
public class ApiExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail notFound(BookNotFoundException e) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        problem.setTitle("Book not found");
        problem.setType(URI.create("https://api.example.com/problems/book-not-found"));
        return problem;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail invalid(MethodArgumentNotValidException e) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request has invalid fields");
        problem.setTitle("Validation failed");
        problem.setProperty("errors", e.getBindingResult().getFieldErrors().stream()
            .map(error -> Map.of("field", error.getField(), "message", error.getDefaultMessage()))
            .toList());
        return problem;
    }

    @ExceptionHandler(Exception.class)                       // last resort: a bug
    public ProblemDetail unexpected(Exception e) {
        log.error("Unhandled exception", e);                 // full details in the log only
        return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
    }
}

How Spring picks a handler: it looks for handlers whose declared type matches the thrown exception, and the closest match in the class hierarchy wins. A BookNotFoundException goes to notFound, not to the Exception catch-all. Handlers in the controller itself take precedence over advice. Handler methods can take the exception, the HttpServletRequest, a Locale and more as parameters, and return a ProblemDetail, a ResponseEntity or any object.

ProblemDetail and RFC 9457

Inventing your own error JSON for every project means every client must learn a new format. RFC 9457, Problem Details for HTTP APIs (which replaced RFC 7807), standardizes it. A problem response has the media type application/problem+json and these members:

Member Meaning
type A URI identifying the problem type (default about:blank); may point to documentation
title Short, human-readable summary of the problem type (same for every occurrence)
status The HTTP status code, repeated for convenience
detail Human-readable explanation of this occurrence
instance A URI for this occurrence, often the request path
extensions Any extra members, such as errors with field details

Spring's ProblemDetail class models exactly this, and Spring MVC writes it with the right content type. When you leave instance empty, Spring fills in the request path. Your own exceptions can carry their problem detail by extending ErrorResponseException, so no handler is needed for them at all.

Spring's built-in exceptions (MethodArgumentNotValidException, HttpRequestMethodNotSupportedException, NoResourceFoundException...) can be rendered as problem details too. Either set

PROPERTIES
spring.mvc.problemdetails.enabled=true

or extend ResponseEntityExceptionHandler in your advice and override only the methods you want to customize, such as handleMethodArgumentNotValid. Then every error your API produces, from a missing parameter to a crashed handler, has the same shape.

The last program is a small end-to-end version: an "advice" object with @ExceptionHandler methods, a resolver that picks the closest handler by walking the exception's class hierarchy, and an HTTP server that returns application/problem+json. The client triggers a validation error, a not-found error, a conflict and a bug.

Java @ExceptionHandler and ProblemDetail responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every failure has the same shape, the right status and the right media type. The BookNotFoundException was handled by the NotFoundException handler (distance 1), because there's no handler for the exact type. And the bug in /api/report produced a generic 500 for the client, while the details went to the server log (standard error here).

Guidelines for production APIs

  • Validate at the boundary. Use Bean Validation on request DTOs for shape rules (required, length, format). Check business rules ("ISBN already exists", "not enough stock") in the service, and signal them with domain exceptions that the advice maps to 409, 422 or 404.
  • Report all field errors at once, with field paths, so clients can fix everything in one round trip.
  • Choose statuses carefully. 400 for malformed or invalid input, 404 for missing resources, 409 for conflicts with current state, 422 Unprocessable Content if your team reserves 400 for syntax errors only, 500 only for bugs. More in REST API Design.
  • Never leak internals. No stack traces, SQL, class names or exception messages from unexpected errors in responses. Boot's defaults already hide them (server.error.include-stacktrace=never, include-message=never); keep it that way in production. Log the details with a request or trace id, and consider returning that id as a problem extension member so support can find the log entry. See Web Security Basics.
  • Don't swallow exceptions. A handler that returns 200 with {"success": false} breaks HTTP semantics, caching and monitoring.
  • Test your error paths. A @WebMvcTest that posts invalid JSON and checks the 400 and the problem body is cheap and catches regressions; see Testing Spring Boot Applications.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A record component is declared as @Size(min = 8) String password and the client omits password. Is the request valid?

    Only @NotNull, @NotEmpty and @NotBlank reject null. Combine constraints to express "required and at least 8 characters".
  2. 2. An order record has List<OrderLine> lines, and OrderLine has @Positive int quantity. A line with quantity 0 is posted with @Valid @RequestBody NewOrder. What happens?

    Cascading must be requested with @Valid, for example List<@Valid OrderLine> lines.
  3. 3. A @RestControllerAdvice has handlers for NotFoundException and for Exception. A controller throws BookNotFoundException, which extends NotFoundException. Which handler runs?

    Spring chooses the handler whose declared exception type is closest to the thrown type.
  4. 4. In an RFC 9457 problem response, what is the difference between title and detail?

    title stays constant for a problem type (for example "Validation failed"), while detail describes what went wrong in this request.
  5. 5. What should a catch-all @ExceptionHandler(Exception.class) return to the client?

    Unexpected exceptions are bugs. Clients get a generic message; developers get the details in the logs.

Summary

  • Add spring-boot-starter-validation and declare rules with Jakarta Bean Validation annotations: @NotNull, @NotBlank, @Size, @Min, @Email, @Pattern, @Past...
  • null passes every constraint except @NotNull, @NotEmpty and @NotBlank; use wrapper types in input records.
  • @Valid @RequestBody validates the body and throws MethodArgumentNotValidException (400); constraints on parameters are validated by Spring MVC's built-in method validation (HandlerMethodValidationException).
  • Cascade into nested objects and list elements with @Valid; violations carry paths like lines[1].quantity.
  • Custom constraints are an annotation with @Constraint(validatedBy = ...) plus a ConstraintValidator.
  • Centralize error handling in @RestControllerAdvice with @ExceptionHandler methods; the closest exception type wins.
  • Return ProblemDetail (RFC 9457, application/problem+json) for every error; enable spring.mvc.problemdetails.enabled or extend ResponseEntityExceptionHandler for Spring's own exceptions.
  • Log unexpected errors with details, but return only a generic 500 to clients.

Next: Spring Data JPA replaces the in-memory map behind this API with a real database and repositories that write their own queries.