Chapter 07

Validation and error handling

Your error responses are part of your API contract, and they are the part clients hit on a bad day. Design them once, centrally, and every endpoint gets them for free.

⏱ 18 min readLevel: intermediate

Turning validation on

Bean Validation is not included in spring-boot-starter-web — it needs its own starter. Adding the annotations without it produces no error and no validation, which is a memorable afternoon.

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

The built-in constraints

AnnotationApplies toChecks
@NotNullanynot null (an empty string passes)
@NotEmptyString, Collection, Map, arraynot null and size > 0
@NotBlankStringnot null and contains non-whitespace
@SizeString, Collection, Map, arraylength between min and max
@Min / @Maxintegral numbersnumeric bounds
@DecimalMin / @DecimalMaxBigDecimal, Stringbounds without precision loss
@Positive, @PositiveOrZeronumberssign
@Digitsnumbersinteger and fraction digit counts
@EmailStringloose email shape
@PatternStringregex
@Past, @Futuredatesrelative to now
@Validnested objectcascades validation into it
@NotNull vs @NotEmpty vs @NotBlank

"" passes @NotNull. " " passes both @NotNull and @NotEmpty. For user-supplied text you almost always want @NotBlank.

Validating at each layer

Request bodies

catalog/dto/BookRequest.java
public record BookRequest(

        @NotBlank(message = "Title is required")
        @Size(max = 200, message = "Title must be at most {max} characters")
        String title,

        @NotNull
        @Positive
        Long authorId,

        @NotNull
        @DecimalMin(value = "0.00", inclusive = false)
        @Digits(integer = 8, fraction = 2)
        BigDecimal price,

        @Valid                                    // cascade into the nested record
        DimensionsRequest dimensions,

        @Size(max = 5)
        Set<@NotBlank String> categories) {       // validate the ELEMENTS too

    public record DimensionsRequest(@Positive int widthMm, @Positive int heightMm) { }
}
the controller side
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody BookRequest request) {
    // if validation fails, this method is never entered:
    // MethodArgumentNotValidException is thrown first
}

Path variables and query parameters

These need @Validated on the class, because the constraints sit on method parameters rather than on an object.

catalog/BookController.java
@RestController
@RequestMapping("/api/books")
@Validated                                   // enables method-parameter validation
public class BookController {

    @GetMapping("/{id}")
    public BookResponse findById(@PathVariable @Positive Long id) { }

    @GetMapping
    public Page<BookResponse> search(
            @RequestParam @Size(min = 2, max = 100) String q,
            @RequestParam(defaultValue = "0")  @PositiveOrZero int page,
            @RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) { }
}

These throw HandlerMethodValidationException (Boot 3.2+) rather than MethodArgumentNotValidException — both need handling, as shown below.

Service-layer validation

catalog/BookService.java
@Service
@Validated
public class BookService {

    public Book create(@Valid CreateBookCommand command) {
        // reachable from anywhere, not just HTTP — a useful safety net
    }
}

Custom constraints

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

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;              // null-handling belongs to @NotNull
        }
        String digits = value.replace("-", "");
        if (digits.length() != 13 || !digits.chars().allMatch(Character::isDigit)) {
            return false;
        }
        int sum = 0;
        for (int i = 0; i < 12; i++) {
            sum += (digits.charAt(i) - '0') * (i % 2 == 0 ? 1 : 3);
        }
        int check = (10 - (sum % 10)) % 10;
        return check == digits.charAt(12) - '0';
    }
}
Validators are Spring beans

A ConstraintValidator can use constructor injection, so a uniqueness check against a repository is possible. Use that sparingly — a database round trip inside validation is easy to duplicate and hard to make race-free. Uniqueness is usually better enforced by a database constraint and mapped to a 409.

Cross-field validation

class-level constraint
@ValidDateRange                              // custom class-level annotation
public record PromotionRequest(@NotNull LocalDate startsOn,
                               @NotNull LocalDate endsOn) { }

public class DateRangeValidator
        implements ConstraintValidator<ValidDateRange, PromotionRequest> {

    @Override
    public boolean isValid(PromotionRequest value, ConstraintValidatorContext context) {
        if (value.startsOn() == null || value.endsOn() == null) {
            return true;
        }
        boolean valid = !value.endsOn().isBefore(value.startsOn());
        if (!valid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("endsOn must not be before startsOn")
                   .addPropertyNode("endsOn")        // attach the error to a field
                   .addConstraintViolation();
        }
        return valid;
    }
}

Validation groups

different rules for create and update
public interface OnCreate { }
public interface OnUpdate { }

public record BookRequest(
        @Null(groups = OnCreate.class)         // must be absent when creating
        @NotNull(groups = OnUpdate.class)      // required when updating
        Long id,

        @NotBlank(groups = { OnCreate.class, OnUpdate.class })
        String title) { }

@PostMapping
public BookResponse create(@Validated(OnCreate.class) @RequestBody BookRequest request) { }

@PutMapping("/{id}")
public BookResponse update(@Validated(OnUpdate.class) @RequestBody BookRequest request) { }

Error responses: use ProblemDetail

Spring 6 supports RFC 9457 (formerly RFC 7807) natively. It gives you a standard, machine-readable error shape instead of a bespoke one per project.

what a client receives
{
  "type": "https://bitsnippets.com/errors/validation",
  "title": "Request validation failed",
  "status": 400,
  "detail": "2 fields are invalid",
  "instance": "/api/books",
  "timestamp": "2026-08-17T10:24:31.882Z",
  "traceId": "3f2a1c9e5b7d4a10",
  "errors": [
    { "field": "title", "message": "Title is required", "rejectedValue": "" },
    { "field": "price", "message": "must be greater than 0", "rejectedValue": -5 }
  ]
}

One @RestControllerAdvice for the whole application

common/error/GlobalExceptionHandler.java
package com.bitsnippets.bookstore.common.error;

import org.springframework.http.*;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.net.URI;
import java.time.Instant;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

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

    /* ---------- 400: bean validation on @RequestBody ---------- */
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {

        List<FieldError> errors = ex.getBindingResult().getFieldErrors().stream()
                .map(fe -> new FieldError(fe.getField(),
                                          fe.getDefaultMessage(),
                                          fe.getRejectedValue()))
                .toList();

        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.BAD_REQUEST, errors.size() + " field(s) are invalid");
        problem.setTitle("Request validation failed");
        problem.setType(URI.create("https://bitsnippets.com/errors/validation"));
        problem.setProperty("errors", errors);
        decorate(problem);

        return ResponseEntity.badRequest().body(problem);
    }

    /* ---------- 400: constraints on method parameters ---------- */
    @ExceptionHandler(ConstraintViolationException.class)
    ProblemDetail handleConstraintViolation(ConstraintViolationException ex) {
        List<FieldError> errors = ex.getConstraintViolations().stream()
                .map(v -> new FieldError(v.getPropertyPath().toString(),
                                         v.getMessage(),
                                         v.getInvalidValue()))
                .toList();

        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.BAD_REQUEST, "Invalid request parameters");
        problem.setProperty("errors", errors);
        decorate(problem);
        return problem;
    }

    /* ---------- 404 ---------- */
    @ExceptionHandler(ResourceNotFoundException.class)
    ProblemDetail handleNotFound(ResourceNotFoundException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.NOT_FOUND, ex.getMessage());
        problem.setTitle("Resource not found");
        problem.setType(URI.create("https://bitsnippets.com/errors/not-found"));
        decorate(problem);
        return problem;
    }

    /* ---------- 409 ---------- */
    @ExceptionHandler(DataIntegrityViolationException.class)
    ProblemDetail handleConflict(DataIntegrityViolationException ex) {
        log.warn("Integrity violation", ex);
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.CONFLICT, "That value already exists");
        problem.setTitle("Conflict");
        decorate(problem);
        return problem;
    }

    @ExceptionHandler(OptimisticLockingFailureException.class)
    ProblemDetail handleStale(OptimisticLockingFailureException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.CONFLICT, "The resource was modified by someone else. Reload and retry.");
        decorate(problem);
        return problem;
    }

    /* ---------- 500: the catch-all ---------- */
    @ExceptionHandler(Exception.class)
    ProblemDetail handleUnexpected(Exception ex) {
        String reference = UUID.randomUUID().toString();
        log.error("Unhandled exception [ref={}]", reference, ex);

        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
                HttpStatus.INTERNAL_SERVER_ERROR,
                "Something went wrong. Quote reference " + reference + " to support.");
        problem.setTitle("Internal server error");
        problem.setProperty("reference", reference);
        decorate(problem);
        return problem;
    }

    private void decorate(ProblemDetail problem) {
        problem.setProperty("timestamp", Instant.now());
        Span span = Span.current();
        if (span.getSpanContext().isValid()) {
            problem.setProperty("traceId", span.getSpanContext().getTraceId());
        }
    }

    record FieldError(String field, String message, Object rejectedValue) { }
}
Never put the exception message in a 500 response

Stack traces and exception messages leak table names, file paths, library versions and sometimes credentials. Log the detail with a correlation reference, return the reference to the client, and keep everything else server-side. The handler above does exactly that.

Domain exceptions

common/error/ResourceNotFoundException.java
public class ResourceNotFoundException extends RuntimeException {

    private final String resource;
    private final Object id;

    public ResourceNotFoundException(String resource, Object id) {
        super("%s %s was not found".formatted(resource, id));
        this.resource = resource;
        this.id = id;
    }
}

public class BookNotFoundException extends ResourceNotFoundException {
    public BookNotFoundException(Long id) {
        super("Book", id);
    }
}

Extend RuntimeException, not Exception: checked exceptions do not trigger a Spring rollback by default (chapter 9) and they pollute every signature between the throw site and the handler.

Externalising messages

src/main/resources/messages.properties
book.title.required=A title is required
book.price.positive=Price must be greater than zero
book.isbn.invalid=That ISBN is not valid
referencing them
public record BookRequest(
        @NotBlank(message = "{book.title.required}")
        String title,

        @Positive(message = "{book.price.positive}")
        BigDecimal price) { }

Add messages_de.properties, messages_fr.properties and Spring resolves them from the request's Accept-Language header.

Tightening Boot's default error page

application.yml
server:
  error:
    include-message: never          # never leak exception messages
    include-binding-errors: never
    include-stacktrace: never
    include-exception: false
    whitelabel:
      enabled: false

spring:
  mvc:
    problemdetails:
      enabled: true                 # ProblemDetail for Spring's own exceptions too
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false           # required for the above to produce a 404 exception

Testing the error contract

BookControllerValidationTest.java
@WebMvcTest(BookController.class)
class BookControllerValidationTest {

    @Autowired MockMvc mvc;
    @MockitoBean BookService bookService;

    @Test
    void rejectsBlankTitleWithFieldLevelDetail() throws Exception {
        String body = """
            { "title": "", "authorId": 1, "price": 10.00 }
            """;

        mvc.perform(post("/api/books")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(body))
           .andExpect(status().isBadRequest())
           .andExpect(header().string("Content-Type", "application/problem+json"))
           .andExpect(jsonPath("$.title").value("Request validation failed"))
           .andExpect(jsonPath("$.errors[?(@.field == 'title')]").exists());
    }

    @Test
    void returns404ProblemForMissingBook() throws Exception {
        when(bookService.require(99L)).thenThrow(new BookNotFoundException(99L));

        mvc.perform(get("/api/books/99"))
           .andExpect(status().isNotFound())
           .andExpect(jsonPath("$.detail").value("Book 99 was not found"));
    }
}

Checklist

  • spring-boot-starter-validation is actually on the classpath.
  • @Valid on every @RequestBody; @Validated on classes with parameter constraints.
  • One @RestControllerAdvice; no try/catch in controllers.
  • Field-level errors returned as structured data, not a concatenated string.
  • 500 responses carry a reference, never a message or stack trace.
  • Every custom exception maps to a deliberate status code.

You put @Positive on a @PathVariable but invalid values still reach the method. Why?

Constraints on method parameters are enforced by a proxy that Spring only creates when the class is annotated @Validated. Without it the annotations are inert. Constraints on the fields of an object bound with @Valid work without it.