Spring Boot in Motion Spring Boot Intermediate

Validation: fail fast at the edge

Garbage in, structured rejection out

A controller is a boundary. Inputs should be validated before they reach service code — that way the service has already been handed clean domain values and can focus on business rules. Spring's Bean Validation integration (@Valid + JSR-380 annotations) makes this almost free.

record CreateInvoiceRequest(
    @NotBlank String customerName,
    @Email    String email,
    @NotNull @Positive Long amountCents,
    @NotBlank String currency
) {}

@PostMapping
ResponseEntity<InvoiceDto> create(@Valid @RequestBody CreateInvoiceRequest req) { /* ... */ }

Translate MethodArgumentNotValidException once

Write a single @ControllerAdvice that converts validation failures into your standard error response shape. Clients get consistent, actionable messages with field-level detail; your controllers remain a handful of lines each.

Takeaways

  • Validate at the edge so service code can trust its inputs.
  • Map validation failures to a uniform error response in one place.
  • Reserve 500 for genuine surprise; most bad input is 400 or 422.

Enjoying This Lesson?

Your support helps create more comprehensive courses and lessons like this one. Help me build better learning experiences for everyone.

Support Awashyak