Validation and error contracts
What you will learn
Treat malformed requests, invalid values, missing records and conflicting state as different outcomes. A stable error contract helps clients recover without revealing internal details.
- Separate binding, validation and domain errors.
- Map missing and conflicting state to explicit status codes.
- Explain Problem Details and safe messages.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. MVC examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Reject invalid input before mutation
import java.util.*;final class InventoryStore { private record Entry(String sku, String name, int quantity, String internalNote) {} public record Item(String sku, String name, int quantity) {} public record Page(List<Item> items, int page, int size, int total) { public Page { items = List.copyOf(items); } } public static final class Missing extends RuntimeException { private static final long serialVersionUID = 1L; } public static final class Conflict extends RuntimeException { private static final long serialVersionUID = 1L; } private final Map<String, Entry> entries = new TreeMap<>(); public InventoryStore() { create("A1", "Notebook", 5); create("B2", "Pencil", 8); create("C3", "Notebook", 2); } private static Item dto(Entry e) { return new Item(e.sku(), e.name(), e.quantity()); } public synchronized Item get(String sku) { Entry e = entries.get(sku); if (e == null) throw new Missing(); return dto(e); } public synchronized Item create(String sku, String name, int quantity) { if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || name == null || name.isBlank() || name.length() > 80 || quantity < 0 || quantity > 10000) throw new IllegalArgumentException("Invalid item"); if (entries.containsKey(sku)) throw new Conflict(); Entry e = new Entry(sku, name, quantity, "warehouse-only"); entries.put(sku, e); return dto(e); } public synchronized Page page(int page, int size, String sort) { if (page < 0 || page > 10000 || size < 1 || size > 100) throw new IllegalArgumentException("Invalid page"); Comparator<Item> order = switch (sort) { case "sku" -> Comparator.comparing(Item::sku); case "name" -> Comparator.comparing(Item::name).thenComparing(Item::sku); default -> throw new IllegalArgumentException("Invalid sort"); }; List<Item> all = entries.values().stream().map(InventoryStore::dto).sorted(order).toList(); int from = Math.min(all.size(), page * size); int to = Math.min(all.size(), from + size); return new Page(all.subList(from, to), page, size, all.size()); }}
public class Main { public static void main(String[] args) {var store = new InventoryStore();try { store.create("D4", "Eraser", -1); } catch (IllegalArgumentException e) { System.out.println("invalid"); }System.out.println(store.page(0, 20, "sku").total());} }Expected output:
invalid3The store rejects invalid quantity before it mutates state. The HTTP 400 mapping is separate.
Validation layers
JSON decoding can fail before controller invocation. @Valid triggers validation of the bound request object when a provider is present. Use Integer with @NotNull to distinguish missing quantity from zero; @Min alone does not reject null. A domain store must still enforce invariants for non-HTTP callers. MVC method validation has a separate exception path for constraints on handler parameters; this lab validates pagination in the store rather than adding method constraints.
Error responses
400 represents invalid request input; 404 means the selected item was not found; 409 indicates a conflict with current state. 415 concerns unsupported request media, 406 unacceptable response media. @RestControllerAdvice and @ExceptionHandler map known errors; ProblemDetail represents RFC 9457 fields such as type, title, status, detail and instance. The HTTP status must agree with the status member if present. Avoid stack traces, raw exception messages and rejected secret values. The lab maps IllegalArgumentException broadly for teaching only; production should use specific domain exceptions so programming bugs are not mislabeled as client errors.
Distinguish missing and duplicate
import java.util.*;final class InventoryStore { private record Entry(String sku, String name, int quantity, String internalNote) {} public record Item(String sku, String name, int quantity) {} public record Page(List<Item> items, int page, int size, int total) { public Page { items = List.copyOf(items); } } public static final class Missing extends RuntimeException { private static final long serialVersionUID = 1L; } public static final class Conflict extends RuntimeException { private static final long serialVersionUID = 1L; } private final Map<String, Entry> entries = new TreeMap<>(); public InventoryStore() { create("A1", "Notebook", 5); create("B2", "Pencil", 8); create("C3", "Notebook", 2); } private static Item dto(Entry e) { return new Item(e.sku(), e.name(), e.quantity()); } public synchronized Item get(String sku) { Entry e = entries.get(sku); if (e == null) throw new Missing(); return dto(e); } public synchronized Item create(String sku, String name, int quantity) { if (sku == null || !sku.matches("[A-Z0-9]{1,12}") || name == null || name.isBlank() || name.length() > 80 || quantity < 0 || quantity > 10000) throw new IllegalArgumentException("Invalid item"); if (entries.containsKey(sku)) throw new Conflict(); Entry e = new Entry(sku, name, quantity, "warehouse-only"); entries.put(sku, e); return dto(e); } public synchronized Page page(int page, int size, String sort) { if (page < 0 || page > 10000 || size < 1 || size > 100) throw new IllegalArgumentException("Invalid page"); Comparator<Item> order = switch (sort) { case "sku" -> Comparator.comparing(Item::sku); case "name" -> Comparator.comparing(Item::name).thenComparing(Item::sku); default -> throw new IllegalArgumentException("Invalid sort"); }; List<Item> all = entries.values().stream().map(InventoryStore::dto).sorted(order).toList(); int from = Math.min(all.size(), page * size); int to = Math.min(all.size(), from + size); return new Page(all.subList(from, to), page, size, all.size()); }}
public class Main { public static void main(String[] args) {var store = new InventoryStore();try { store.get("Z9"); } catch (InventoryStore.Missing e) { System.out.println("404 policy"); }try { store.create("A1", "Replacement", 1); } catch (InventoryStore.Conflict e) { System.out.println("409 policy"); }System.out.println(store.get("A1").quantity());} }Expected output:
404 policy409 policy5The original item survives the conflict. Status strings describe the chosen adapter policy, not actual HTTP responses.
Validate the request DTO
Source-reviewed, NOT RUN. File lab-fixtures/mvc-v39/src/main/java/example/inventory/CreateItem.java; use the companion lab README.
package example.inventory;import jakarta.validation.constraints.*;public record CreateItem(@NotNull @Pattern(regexp="[A-Z0-9]{1,12}") String sku, @NotBlank @Size(max=80) String name, @NotNull @Min(0) @Max(10000) Integer quantity) {}Predicted behavior: Missing quantity, invalid SKU and blank name fail validation.
Bean Validation constraints are applied through @Valid in the controller.
Translate known failures
Source-reviewed, NOT RUN. File lab-fixtures/mvc-v39/src/main/java/example/inventory/InventoryErrors.java; use the companion lab README.
package example.inventory;import org.springframework.http.*;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.*;import org.springframework.http.converter.HttpMessageNotReadableException;import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;@RestControllerAdvicepublic class InventoryErrors { @ExceptionHandler(InventoryStore.Missing.class) ProblemDetail missing() { return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "Item not found"); } @ExceptionHandler(InventoryStore.Conflict.class) ProblemDetail conflict() { return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "SKU already exists"); } @ExceptionHandler({MethodArgumentNotValidException.class, HttpMessageNotReadableException.class, MethodArgumentTypeMismatchException.class, IllegalArgumentException.class}) ProblemDetail invalid() { return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid request"); }}Predicted behavior: Known failures return safe Problem Details.
Do not promise an exact negotiated error media type until MVC tests run.
Common mistakes
Do not catch Throwable, return 200 for failures, or expose a raw SQLException. A validation annotation is not authorization. A Problem Details body must not contradict its status code.
Practice
Attempt to create a blank name, then read an absent SKU; report invalid and missing and prove total remains three.
Expected output:
invalidmissing3Compare with the manual review criteria.
Official reading: Validation · Errors · Problem · HTTP. MVC execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Validation and error contracts — knowledge check
REST API engineering and HTTP contract reasoning.
Why use Integer plus @NotNull for quantity?
Which status fits a duplicate SKU in this contract?
What belongs in a public problem detail?
What does a 415 indicate?
Why validate in the store as well?