Validation and Error Handling¶
Validation protects a boundary; domain invariants protect valid state everywhere. A syntactically valid request may still violate a use-case rule that depends on current state. The DTO mapping and validation guide separates transport, application, domain, and database responsibilities.
record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotNull @PastOrPresent LocalDate publishedOn) {
}
@Valid triggers nested Bean Validation for supported controller arguments.
Use domain constructors or factories to preserve invariants when objects are
created outside HTTP.
Error representation¶
Spring Framework supports ProblemDetail for the Problem Details for HTTP APIs
standard. A centralized advice can translate application exceptions without
exposing stack traces, SQL details, class names, or secrets.
@RestControllerAdvice
final class ApiErrors {
@ExceptionHandler(BookNotFoundException.class)
ProblemDetail notFound(BookNotFoundException exception) {
ProblemDetail detail = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
detail.setTitle("Book not found");
detail.setDetail("No book is available for the supplied identifier.");
return detail;
}
}
Do not return a raw exception message merely because it is convenient. Define a stable error type or code when clients must branch on an error.
Failure taxonomy¶
- malformed representation or type mismatch: client request error;
- field constraint failure: structured validation error;
- missing resource: absence under the API's disclosure policy;
- state conflict: valid input incompatible with current state;
- dependency timeout/unavailability: transient server-side failure;
- unexpected defect: generic server error plus an internal correlation identifier.
See the official Spring MVC validation and error response documentation.