Skip to content
Visual explainer 3h to learn 3 steps

Validation & global error handling

Validate input and return consistent error responses.

By Invicly Tech, , in Backend Java Development. About 10 minutes to read.

Topic 18 of 29

In short

Bean Validation annotations declare rules on DTO fields, and @Valid makes Spring enforce them before your code runs. A global @RestControllerAdvice turns every error into the same JSON shape.

Explained simply

Never trust input. A client may send an empty name, an email without an @ sign, a negative quantity, or a 10 MB string. If your code does not check, bad data ends up in the database or causes strange errors deep in your logic.

Bean Validation lets you write the rules as annotations right on your DTO fields: @NotBlank on a name, @Email on an email, @Positive on a quantity. Add @Valid to the controller parameter and Spring checks every rule before your method even starts.

When a rule fails, Spring throws an exception instead of calling your method. By default the client gets a 400 Bad Request. The next step is making that error useful: say which field failed and why, in a format every endpoint shares.

That is the job of a global error handler. One class annotated with @RestControllerAdvice catches exceptions from all controllers and turns each kind into a clean JSON response. Clients can then handle errors the same way everywhere.

Press Play on a diagram to walk through it one step at a time.

FlowWhen validation fails
  1. 1
    Request arrives

    JSON body with an invalid email

  2. 2
    @Valid checks DTO

    Annotations like @NotBlank and @Email run

  3. 3
    Exception thrown

    MethodArgumentNotValidException, controller is skipped

  4. 4
    Advice handles it

    @ExceptionHandler in @RestControllerAdvice

  5. 5
    400 error body

    Consistent JSON listing each bad field

SequenceAn invalid request, start to finish
Client
Spring MVC
Validator
Error advice
  1. 1POST /users { "email": "bad" }
    Client to Spring MVC: POST /users { "email": "bad" }
  2. 2validate CreateUserRequest
    Spring MVC to Validator: validate CreateUserRequest
  3. 3email: must be a well-formed email
    Validator to Spring MVC: email: must be a well-formed email
  4. 4MethodArgumentNotValidException
    Spring MVC to Error advice: MethodArgumentNotValidException
  5. 5400 problem+json with field errors
    Error advice to Client: 400 problem+json with field errors

In depth

The common constraints and how they treat null

Add spring-boot-starter-validation to the build; the web starter does not include it, and without it every annotation is silently ignored. The most used constraints: @NotNull, @NotEmpty and @NotBlank (see the diagram), @Size(min, max) for strings and collections, @Min, @Max, @Positive and @PositiveOrZero for numbers, @Email, @Pattern(regexp = ...) for formats, @Past and @Future for dates, and @Digits(integer, fraction) for amounts.

An important rule: almost every constraint except the @Not... family treats null as valid. @Email on a null field passes, and @Size(min = 3) on null passes too. That is deliberate, so optional fields can be validated only when present. For a required field, combine them: @NotBlank @Email String email.

Compare@NotNull vs @NotEmpty vs @NotBlank
@NotNull
  • Rejects null
  • Accepts ""
  • Accepts " "
  • Any type
@NotEmpty
  • Rejects null
  • Rejects ""
  • Accepts " "
  • Strings, collections, maps, arrays
@NotBlank
  • Rejects null
  • Rejects ""
  • Rejects " "
  • Strings only

Where validation runs and what it throws

@Valid on a @RequestBody parameter validates the object and throws MethodArgumentNotValidException on failure. Nested objects are validated only if the field also has @Valid, and items in a list need List<@Valid ItemRequest>. Without that, a broken nested address passes silently.

Constraints directly on method parameters, such as @PathVariable @Positive long id or @RequestParam @Max(100) int size, use method validation. Since Spring Framework 6.1, controllers apply it automatically and raise HandlerMethodValidationException; older setups put @Validated on the class and got ConstraintViolationException. You can also put @Validated on a service so its methods are checked, which protects rules that do not come from HTTP, such as messages from a queue. Handle all of these in one advice so the client sees the same shape.

  • @Valid on the body parameter
  • @Valid on nested fields and List<@Valid T>
  • Parameter constraints: HandlerMethodValidationException (Spring 6.1+)

Custom and cross-field constraints

When the built-ins are not enough, write your own constraint. It has two parts: an annotation marked @Constraint(validatedBy = SkuValidator.class) with message, groups and payload attributes, and a class implementing ConstraintValidator<ValidSku, String> whose isValid method returns true or false. Return true for null and let @NotNull handle required checks, matching the built-in style.

For rules that involve two fields, such as an end date after a start date or a password matching its confirmation, put the constraint on the class instead of a field. The validator then receives the whole object. On a record, a simpler alternative is a boolean method annotated with @AssertTrue, such as @AssertTrue boolean isRangeValid(), which Bean Validation treats as a property. Messages can come from a ValidationMessages.properties file, which allows translation.

A standard error body: ProblemDetail

RFC 9457 (which replaced RFC 7807) defines a standard JSON error format called problem details, with the media type application/problem+json. It has a few standard fields: type (a URI naming the error kind), title, status, detail and instance (the request path), and you may add your own, such as an errors map of field messages.

Spring supports this with the ProblemDetail class. Return it from an @ExceptionHandler, or throw ErrorResponseException. Setting spring.mvc.problemdetails.enabled=true makes Spring's own exceptions, such as a 405 or a 415, use the format too. You can extend ResponseEntityExceptionHandler in your advice to inherit handlers for all built-in MVC exceptions and override only what you want to change.

  • ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, msg)
  • problem.setProperty("errors", fieldErrors)
  • spring.mvc.problemdetails.enabled=true

Designing the global handler

Map each kind of failure to one status: validation errors to 400, your NotFoundException to 404, a duplicate or version clash to 409, an access problem to 403. Put these mappings in a single @RestControllerAdvice. Keep the domain code clean: services throw meaningful exceptions and know nothing about HTTP.

Add a last handler for Exception that returns 500 with a generic message and logs the full stack trace on the server, ideally with a request or trace id that you also put in the response. Clients can quote that id when they report a problem. Never return stack traces, SQL or class names to clients: they help attackers and confuse users. Spring Boot's defaults already hide them, with server.error.include-stacktrace set to never.

Learn it in 3 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Validate DTOs with Bean Validation annotations~1h
  2. 2
    Handle errors with @ControllerAdvice~1h
  3. 3
    Return a consistent error response body~1h

Key points

  • Put constraints like @NotBlank, @Email, @Size and @Min on DTO fields.
  • Add @Valid to the @RequestBody parameter or nothing is validated.
  • Handle exceptions once in @RestControllerAdvice instead of in every controller.
  • Return one error format everywhere, for example status, message and field errors.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
record CreateUserDto(@NotBlank String name, @Email String email, @Min(18) int age) {}

@RestControllerAdvice
class ApiErrors {
  @ExceptionHandler(MethodArgumentNotValidException.class)
  ResponseEntity<Map<String, Object>> invalid(MethodArgumentNotValidException ex) {
    Map<String, String> fields = new HashMap<>();
    ex.getBindingResult().getFieldErrors()
        .forEach(e -> fields.put(e.getField(), e.getDefaultMessage()));
    return ResponseEntity.badRequest().body(Map.of("status", 400, "errors", fields));
  }
}

One advice for validation and not-found errors

Step 1: a NotFoundException thrown anywhere becomes a 404 ProblemDetail with a clear message. Step 2: validation failures become a 400 ProblemDetail with an errors map from field to message. Step 3: anything else becomes a 500 with a generic message, while the real error is logged. Every endpoint now returns the same error shape without any try-catch in controllers.

java
@RestControllerAdvice
class ApiErrorHandler {
  private static final Logger log = LoggerFactory.getLogger(ApiErrorHandler.class);

  @ExceptionHandler(NotFoundException.class)
  ProblemDetail notFound(NotFoundException ex) {
    return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  ProblemDetail invalid(MethodArgumentNotValidException ex) {
    var pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Validation failed");
    var errors = new TreeMap<String, String>();
    ex.getBindingResult().getFieldErrors().forEach(f -> errors.put(f.getField(), f.getDefaultMessage()));
    pd.setProperty("errors", errors);
    return pd;
  }

  @ExceptionHandler(Exception.class)
  ProblemDetail unexpected(Exception ex) {
    log.error("Unhandled error", ex);
    return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR, "Unexpected error");
  }
}

A booking request with nested and cross-field rules

A booking has a guest and a date range. Step 1: field constraints check each value. Step 2: @Valid on the guest field makes the nested Guest rules run too. Step 3: an @AssertTrue method checks that checkOut is after checkIn; if it is false, the error is reported under the name validRange. Step 4: with @Valid on the controller parameter, all rules run before the service sees the request.

java
record Guest(@NotBlank String name, @NotBlank @Email String email) {}

record BookingRequest(
    @NotNull @Valid Guest guest,
    @NotNull @FutureOrPresent LocalDate checkIn,
    @NotNull LocalDate checkOut,
    @Min(1) @Max(8) int guests) {

  @AssertTrue(message = "checkOut must be after checkIn")
  boolean isValidRange() {
    return checkIn == null || checkOut == null || checkOut.isAfter(checkIn);
  }
}

// @PostMapping("/bookings") ... create(@Valid @RequestBody BookingRequest req)

Quick reference

  • Add spring-boot-starter-validation or annotations are ignored
  • @NotBlank for required text; @NotNull for required objects and numbers
  • Most constraints accept null; combine with @NotNull for required fields
  • Nested objects need @Valid on the field; lists need List<@Valid T>
  • @Valid body failure: MethodArgumentNotValidException, 400 by default
  • ProblemDetail gives RFC 9457 error bodies (application/problem+json)
  • One @RestControllerAdvice maps exceptions to status codes for all controllers
  • Never return stack traces; log them with a request id instead

Common mistakes

  • Forgetting @Valid, so annotations are silently ignored.
  • Returning stack traces to clients in error responses.
  • Each controller inventing its own error JSON shape.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A field annotated @NotEmpty receives " " (three spaces). What happens?

Question 2

2A DTO field is annotated only with @Email and the client omits it (null). What happens?

Question 3

3An order DTO has a List<Item> items, and Item has @Positive quantity. A negative quantity gets through. Why?

Question 4

4Which standard defines the problem+json error format that Spring's ProblemDetail follows?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a SignupRequest record: username 3 to 20 characters, a valid email, a password of at least 12 characters, and an age of at least 16.

  2. Exercise 2medium

    Make GET /api/products/{id} reject ids below 1 with a 400, and map your ProductNotFoundException to a 404 ProblemDetail.

  3. Exercise 3hard

    Create a custom @Sku constraint that accepts codes like AB-1234 (two capital letters, a dash, four digits) and treats null as valid.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between @Valid and @Validated?
@Valid is the Jakarta standard and triggers validation, including cascading into nested objects. @Validated is Spring's variant that also supports validation groups and enables method validation when placed on a class.
Should I validate in the service layer as well?
Validate input format at the edge with DTO annotations, and enforce business rules, such as stock or uniqueness, in the service, because they need data and can be reached from other entry points too.
How do I change the default error messages?
Set message on the annotation, for example @Size(min = 3, message = "too short"), or use a key like {user.name.size} defined in ValidationMessages.properties.
Why does my uniqueness check still allow duplicates?
A check like existsByEmail can race with another request. Keep a UNIQUE constraint in the database and map the resulting DataIntegrityViolationException to a 409.

Go deeper

ShareXLinkedInWhatsApp