Validation and error handling
An API must reject bad input with clear messages, and report every failure in a consistent format. Spring Boot combines Jakarta Bean Validation (annotations such as @NotBlank and @Min) with @RestControllerAdvice for central error handling, and supports the Problem Details standard (RFC 9457) out of the box.
Declaring constraints
Add spring-boot-starter-validation, then annotate the request record:
import jakarta.validation.constraints.*;
import java.math.BigDecimal;
public record ProductRequest(
@NotBlank @Size(max = 100) String name,
@NotNull @DecimalMin(value = "0.01") @Digits(integer = 8, fraction = 2) BigDecimal price,
@Min(0) int stock,
@NotBlank String category) {
}| Constraint | Checks |
|---|---|
@NotNull |
Not null |
@NotBlank |
A string with at least one non-space character |
@NotEmpty |
Not null and not empty (strings, collections) |
@Size(min, max) |
Length of a string or collection |
@Min, @Max, @Positive, @PositiveOrZero |
Number ranges |
@DecimalMin, @DecimalMax, @Digits |
Decimal ranges and precision |
@Email, @Pattern(regexp = "…") |
Formats |
@Past, @Future |
Dates |
@Valid |
Validate a nested object or list elements too |
Then ask Spring to validate the body with @Valid:
@PostMapping
public ResponseEntity<ProductResponse> create(@Valid @RequestBody ProductRequest request) { … }
@PutMapping("/{id}")
public ProductResponse update(@PathVariable Long id, @Valid @RequestBody ProductRequest request) { … }Invalid requests never reach your method: Spring throws MethodArgumentNotValidException, which by default becomes a 400 response.
Central error handling with @RestControllerAdvice
A class annotated @RestControllerAdvice handles exceptions thrown by any controller. Each @ExceptionHandler method turns one exception type into a response. Spring's ProblemDetail class produces RFC 9457 JSON with the application/problem+json content type:
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(Long id) {
super("Product " + id + " does not exist");
}
}import java.net.URI;
import java.util.Comparator;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
record FieldProblem(String field, String message) {}
@ExceptionHandler(ProductNotFoundException.class)
public ProblemDetail notFound(ProductNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Product not found");
problem.setType(URI.create("https://api.myshop.example/problems/not-found"));
return problem;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
.map(e -> new FieldProblem(e.getField(), e.getDefaultMessage()))
.sorted(Comparator.comparing(FieldProblem::field))
.toList());
return problem;
}
}curl localhost:8080/api/products/99
curl -X POST localhost:8080/api/products -H "Content-Type: application/json" \
-d '{"name":"","price":-1,"stock":-5}'{"detail":"Product 99 does not exist","status":404,"title":"Product not found","type":"https://api.myshop.example/problems/not-found"}
{"detail":"Request validation failed","status":400,"title":"Invalid request","errors":[{"field":"category","message":"must not be blank"},{"field":"name","message":"must not be blank"},{"field":"price","message":"must be greater than or equal to 0.01"},{"field":"stock","message":"must be greater than or equal to 0"}]}Every problem was reported at once, with the field it belongs to. (The service simply throws ProductNotFoundException; it doesn't know anything about HTTP.)
Problem Details for Spring's own errors too
Set one property and Spring MVC's built-in exceptions (unsupported media type, missing parameters, malformed JSON, method not allowed) also use Problem Details:
spring.mvc.problemdetails.enabled=trueFor full control, extend ResponseEntityExceptionHandler in your advice class and override its methods.
A catch-all for unexpected errors
@ExceptionHandler(Exception.class)
public ProblemDetail unexpected(Exception ex) {
log.error("Unexpected error", ex); // full details in the logs
return ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR,
"Something went wrong. Please try again later."); // nothing internal in the response
}Custom constraints and business rules
Annotations cover formats and ranges. Rules that need the database (is this name already taken?) belong in the service, which throws a specific exception that the advice maps to a status:
@Transactional
public Product create(ProductRequest request) {
if (products.existsByNameIgnoreCase(request.name())) {
throw new DuplicateProductException(request.name()); // → 409 Conflict in the advice
}
return products.save(new Product(…));
}You can also write reusable annotations (@Isbn, @StrongPassword) by implementing ConstraintValidator, and validate path or query parameters by adding constraints directly to them (@PathVariable @Positive Long id).
Validation messages
Messages can be customised per constraint (@NotBlank(message = "Name is required")) or translated in ValidationMessages.properties. Clients that need to react programmatically should rely on the field and a stable type or code, not the message text.
Practice
- Add a
DuplicateProductExceptionand map it to409 Conflictwith the title "Product already exists". - Add
@Email String supplierEmail(optional) toProductRequestand check the error for"not-an-email". - Turn on
spring.mvc.problemdetails.enabledand look at the response for a malformed JSON body.
1.What triggers bean validation of a request body?
2.What's the role of @RestControllerAdvice?
3.Where should a rule like "product names must be unique" be enforced?