Validation and Error Handling

Validation and Error Handling in Spring Boot: At a customs post, every shipment stops at an inspection bench before it may proceed.

The Analogy: A Customs Inspection Bench

At a customs post, every shipment stops at an inspection bench before it may proceed. The officer works from a declaration form and a fixed set of rules: the weight must be stated, the declared value must be positive, the commodity code must be a real one, the description must not be blank. The officer does not wave the shipment through on trust; they check it against the rules, and only a shipment that satisfies every rule moves on. This is validation, and the crucial detail is where it happens -- at the bench, before the goods enter the warehouse, not somewhere deep inside after they are already on the shelves.

A Spring controller validates the same way. You annotate the incoming request type with constraints -- this field must not be blank, that number must be positive, this one must be a valid email -- and mark the parameter so the framework checks the declaration before your handler runs. A request that violates a constraint never reaches your code; it is stopped at the bench and turned back. Declaring the rules on the type is far better than scattering hand-written checks through the handler, exactly as a printed rulebook at the bench beats each officer remembering the rules from memory.

A good officer marks up the whole form in one pass. If the weight is missing, the value is negative, and the code is wrong, all three are circled and the form handed back together, so the importer corrects everything and resubmits once. A bad officer rejects on the first error, the importer fixes it and resubmits, the officer finds the second error, and so on -- three round trips for three problems. Bean validation behaves like the good officer: it collects every violation and reports them together, so the client learns everything wrong with one response instead of discovering the problems one painful submission at a time.

Beyond the bench, different problems route to different desks, and this is where the dangerous failure hides. A rule violation goes to the validation desk with a clear code; a request for a consignment that does not exist gets a "no such consignment" slip; a request for cargo the importer is not cleared to handle gets a "not authorised" refusal. Anything the officer cannot classify goes to the supervisor, who stamps a deliberately vague "referred to us" rather than reading out the internal reason -- because the internal reason might tell a smuggler exactly how the checks work. The failure mode is a supervisor whose catch-all "referred" stamp is applied so broadly that it also swallows the "not authorised" refusals: a clear authorisation rejection gets mislabelled as an internal problem, and a security signal that should have been a crisp 403 disappears into a generic 500.

Syntax or Core Structure

You declare validation constraints on the request type and activate them with @Valid on the handler parameter. A violation throws before the handler body runs, and Bean Validation gathers every failed constraint rather than stopping at the first.

public record CreateProductRequest(
    @NotBlank(message = "name is required")     String name,
    @NotNull @Positive                          BigDecimal price,
    @Email                                       String contactEmail,
    @Size(max = 500)                             String description
) {}

@PostMapping
public ProductResponse create(@Valid @RequestBody CreateProductRequest req) {
    return service.create(req);   // reached only if every constraint passed
}

Submitting a request with a blank name, a negative price, and a malformed email -- three violations at once -- produces a single response listing all of them:

Output:

field         message
------------------------------------------
name          name is required
price         price must be positive
contactEmail  must be a valid email
------------------------------------------
violations : 3
status     : 400

All three violations are reported together in one 400 response; the description was within its size limit and raised no error. Because the checks run before the handler, none of your business logic executed on the bad input. Note that @NotBlank is the right choice for the name rather than @NotNull, which would accept an empty or all-spaces string -- for user-supplied text you almost always want blank rejected, not merely null.


Technical Depth: Centralised Handling and the Error Contract

The common constraints

A handful of constraint annotations cover most request validation. Knowing exactly what each one rejects -- and, crucially, what it lets through -- is what stops a "required" field from quietly admitting blank input.

ConstraintRejectsAccepts
@NotNullA null valueAn empty or all-spaces string
@NotBlankNull, empty, or all-spaces textAny string with a non-space character
@PositiveZero and negative numbersAny value strictly above zero
@EmailA string with no valid email shapeA well-formed address
@Size(max)Text longer than the maximumText up to and including the maximum

Mapping exceptions to statuses

The default error response Spring produces leaks internal shape and is hard for clients to parse. Replace it with a @RestControllerAdvice that maps each exception type to a status and a stable body. Each @ExceptionHandler claims a type; a final handler for Exception catches everything else. Dispatching several thrown exceptions through such an advice shows the mapping.

@RestControllerAdvice
public class ApiExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)  // -> 400
    ResponseEntity<ApiError> onValidation(...) { ... }
    @ExceptionHandler(ProductNotFoundException.class)         // -> 404
    ResponseEntity<ApiError> onNotFound(...) { ... }
    @ExceptionHandler(AccessDeniedException.class)            // -> 403
    ResponseEntity<ApiError> onDenied(...) { ... }
    @ExceptionHandler(Exception.class)                        // -> 500 catch-all
    ResponseEntity<ApiError> onUnexpected(Exception ex) { ... }
}

Output:

exception                        status
----------------------------------------
MethodArgumentNotValidException  400
ProductNotFoundException         404
AccessDeniedException            403
IllegalStateException            500 (catch-all)
----------------------------------------
mapped explicitly : 3
fell to catch-all : 1

Three exception types are mapped explicitly to their correct statuses; IllegalStateException matches no specific handler and falls to the Exception catch-all, which returns 500. The catch-all is deliberate and important for security: an unhandled exception can otherwise surface class names, SQL fragments, or file paths in the response, which is reconnaissance handed to an attacker. Log the detail server-side and return a generic message.

A stable error contract, and why collecting beats failing fast

Clients should branch on a stable machine-readable code, not on prose you might reword. A small record -- a code, a human message, and a per-field map -- gives a contract you control. The per-field map is where collected validation errors live, and collecting them all has a concrete payoff measured in round trips.

public record ApiError(String code, String message, Map<String, String> fields) {}

Output:

approach     violations reported  round trips
---------------------------------------------
collect all  3                    1
fail fast    1                    3
---------------------------------------------
trips saved by collecting: 2

With three violations, reporting them all together lets the client fix everything and resubmit once; failing on the first error forces three submit-fix cycles to surface the same three problems. The saving grows with the number of bad fields, and it is why Bean Validation gathers the whole set rather than throwing on the first constraint it fails.

Domain exceptions keep the service HTTP-free

The service layer throws domain exceptions -- a not-found, a conflict -- that carry no HTTP concepts, and the advice maps them to statuses. That separation is what lets the same service back a REST controller, a scheduled job, and a message listener without knowing which is calling it.

public ProductResponse findById(Long id) {
    return repository.findById(id).map(ProductResponse::from)
        .orElseThrow(() -> new ProductNotFoundException(id));
}

Real World Example: A Registration Endpoint and Its Advice

A registration endpoint validates the incoming request and relies on a shared @RestControllerAdvice for error responses. The advice handles validation failures and not-found domain exceptions explicitly, and has a catch-all for everything else. It looks complete. But the endpoint also sits behind an authorisation check, and the advice has no handler for the framework's AccessDeniedException -- so that exception falls through to the catch-all. This program routes four scenarios through the advice.

@RestControllerAdvice
public class ApiExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)  // 400 VALIDATION_FAILED
    @ExceptionHandler(ProductNotFoundException.class)         // 404 NOT_FOUND
    // NOTE: no @ExceptionHandler for AccessDeniedException
    @ExceptionHandler(Exception.class)                        // 500 catch-all
    ResponseEntity<ApiError> handlers() { ... }
}

Output:

scenario                  resolves to
----------------------------------------------
3 invalid fields          400 VALIDATION_FAILED
missing product           404 NOT_FOUND
access denied (no h)      500 (should be 403)
unexpected NPE            500 INTERNAL_ERROR
----------------------------------------------
explicit handlers   : 2
catch-all hits      : 2
misrouted 403->500  : 1

The first two scenarios resolve correctly: invalid fields give a 400 with the validation code, and a missing product gives a 404. The unexpected null-pointer correctly falls to the catch-all and returns a generic 500, hiding its internal detail. Those three are exactly what the advice was designed to do, and a quick test of the happy-path errors would pass.

The third row is the defect. AccessDeniedException is thrown by Spring Security to signal that an authenticated user lacks permission -- it should become a 403. But the advice has no explicit handler for it, so it falls into the @ExceptionHandler(Exception.class) catch-all and comes back as a 500. The client is told the server failed, when in truth the request was correctly refused for lack of permission. A monitoring dashboard now shows phantom 500s, an on-call engineer investigates a server fault that does not exist, and the genuine authorisation signal -- someone repeatedly hitting endpoints they cannot access -- is buried in the noise.

This model simplifies in ways worth naming. It treats handler selection as a flat lookup, whereas Spring actually chooses the most specific matching handler and the ordering of advice classes can matter when several apply. It also ignores that a broad catch-all can swallow exceptions Spring would otherwise translate itself, of which AccessDeniedException is only the most common. The real design flaw it exposes is the tension in a catch-all: you need one so raw exceptions never leak internals, but an over-broad @ExceptionHandler(Exception.class) silently intercepts framework exceptions that carry their own correct status, converting meaningful 401s and 403s into indistinguishable 500s. The fix is to handle the security exceptions explicitly -- or let Spring Security's own entry points handle them -- so the catch-all only ever sees the genuinely unexpected.


Common Mistakes

  1. Writing manual if checks instead of declarative constraints. Hand-written validation scattered through a handler is easy to forget and hard to keep consistent. Annotate the request type with constraints and let @Valid enforce them before the handler runs.
  1. Using @NotNull where you mean @NotBlank. @NotNull accepts an empty string and a string of spaces, so a "required" text field marked @NotNull still admits blank input. For user-supplied text, use @NotBlank.
  1. Forgetting @Valid on the parameter. The constraints on a request type do nothing unless the parameter is marked @Valid. Without it the bad input sails through to your handler, and the annotations are silent decoration.
  1. Returning the default Spring error body. The out-of-the-box error response leaks internal structure and is unstable across versions. Define a stable error contract with a machine-readable code and replace the default with a @RestControllerAdvice.
  1. Leaking exception detail to the client. Returning ex.getMessage() for an unexpected error can expose SQL fragments, class names, or file paths. Log the detail server-side and return a generic message from the catch-all handler.
  1. Making the catch-all too broad. An @ExceptionHandler(Exception.class) that swallows framework exceptions turns a security AccessDeniedException into a 500, hiding a 403. Handle the exceptions that carry their own correct status explicitly, so the catch-all only sees the truly unexpected.
  1. Failing fast instead of collecting violations. Rejecting on the first bad field forces the client through one submit-fix cycle per problem. Let Bean Validation gather every violation and report them together in one response.
  1. Throwing HTTP concepts from the service layer. A service that throws a ResponseStatusException or builds a ResponseEntity is welded to HTTP and cannot be reused by a job or a listener. Throw a domain exception and let the advice map it to a status.
  1. Branching on the error message text. Clients that string-match the human-readable message break when you reword it. Give every error a stable code and let clients branch on that.

Best Practices

  • Declare validation constraints on the request type and activate them with @Valid, so bad input is rejected at the boundary before any business logic runs.
  • Use @NotBlank for required text and reserve @NotNull for fields where an empty string is genuinely acceptable.
  • Define a single stable error contract -- a machine-readable code, a human message, and a per-field map -- and return it from a @RestControllerAdvice shared across all controllers.
  • Keep a catch-all handler for unexpected exceptions that logs the detail and returns a generic message, so raw internals never reach a client.
  • Handle framework exceptions that carry their own status, such as AccessDeniedException, explicitly, so the catch-all does not convert them into misleading 500s.
  • Let validation collect and report every violation at once, sparing clients repeated round trips to discover problems one at a time.
  • Throw domain exceptions from the service layer and map them to statuses in the advice, keeping the service free of HTTP concerns and reusable across entry points.
  • Give clients a stable code to branch on rather than prose, so you can reword messages without breaking anyone.

Practice Exercises

  1. A client sends a negative price and a blank name in one request. Describe the response body your handler produces, and explain why reporting both fields at once beats failing on the first.
  1. A request type marks a required text field @NotNull. Show the input that passes validation but should not, and give the one-annotation change that fixes it.
  1. Your @RestControllerAdvice handles validation and not-found but a permission failure is coming back as a 500. Explain why, and describe the change that restores the correct 403.
  1. Design an ApiError contract for your API, decide which field a client should branch on and why, and explain what would break if clients matched on the human-readable message instead.