Validating Input and Handling Errors Like a Professional
Java & Spring Boot for Beginners · Part 11 of 14
- #Java
- #Spring Boot
- #Beginners
- #validation
- #error-handling
Somewhere between "it works on my machine" and "it works in production" is a question nobody asks until it bites them: what happens when the caller sends garbage? An empty name. A negative price. A field that's just missing. If your answer right now is "it throws a 500 with a stack trace in the response body," you're not alone — that's the default, and it's the thing this part fixes.
We're still working on the same project from Part 9 and Part 10: a REST API backed by Spring Data JPA. Nothing about the domain changes here. What changes is that the API stops trusting its callers, and starts telling them exactly what's wrong when they get it wrong.
The problem with scattered ifs
The naive first instinct is defensive code sprinkled through the controller:
@PostMapping
public Task createTask(@RequestBody Task task) {
if (task.getTitle() == null || task.getTitle().isBlank()) {
throw new RuntimeException("title is required");
}
if (task.getTitle().length() > 200) {
throw new RuntimeException("title too long");
}
// ...and so on, for every field, in every endpoint that accepts one
return taskRepository.save(task);
}
This gets worse linearly with every field and every endpoint, it's easy to
forget a check on the next DTO, and — as written — that RuntimeException
still turns into an ugly, unstructured 500. Two separate problems are tangled
together here: deciding what's invalid, and turning "invalid" into a
response the caller can act on. Spring gives you a clean tool for each.
Bean Validation: declare the rules, don't write them
Spring Boot ships with Bean Validation (the jakarta.validation API,
implemented by Hibernate Validator) via the spring-boot-starter-validation
dependency. Instead of if statements, you annotate the fields on your
request DTO:
public record CreateTaskRequest(
@NotBlank(message = "title is required")
@Size(max = 200, message = "title must be at most 200 characters")
String title,
@Size(max = 2000, message = "description must be at most 2000 characters")
String description,
@NotNull(message = "dueDate is required")
@FutureOrPresent(message = "dueDate cannot be in the past")
LocalDate dueDate
) {}
Then two things turn those annotations into actual enforcement: @Valid on
the controller parameter, and the annotations existing at all — Spring wires
the rest.
@PostMapping
public TaskResponse createTask(@Valid @RequestBody CreateTaskRequest request) {
Task saved = taskRepository.save(toEntity(request));
return toResponse(saved);
}
If any constraint fails, the controller method never runs. Spring throws a
MethodArgumentNotValidException before your code sees the request. That's
the right instinct — reject bad input at the boundary — but by default the
exception still turns into a fairly raw response, and that's what we fix next.
A few annotations cover most real-world cases: @NotNull, @NotBlank,
@NotEmpty, @Size, @Min/@Max, @Email, @Pattern, @Positive,
@PastOrPresent/@FutureOrPresent. Nest @Valid into a field to validate an
embedded object, and add @Validated at the class level if you want
constraints on @RequestParam or @PathVariable too, not just request
bodies.
From exception to response: @ControllerAdvice
Left alone, an unhandled exception becomes whatever Spring Boot's default
error page produces — inconsistent shape, and depending on your profile,
possibly a stack trace in the JSON. The fix is a global exception handler:
one class, annotated @RestControllerAdvice, that intercepts exceptions
thrown anywhere in your controllers and turns them into a response you
control.
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleValidation(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
problem.setTitle("Validation failed");
problem.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
.map(error -> Map.of("field", error.getField(), "message", error.getDefaultMessage()))
.toList());
return problem;
}
@ExceptionHandler(TaskNotFoundException.class)
public ProblemDetail handleNotFound(TaskNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
problem.setTitle("Task not found");
problem.setDetail(ex.getMessage());
return problem;
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex);
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
problem.setTitle("Something went wrong");
problem.setDetail("An unexpected error occurred. Try again or contact support.");
return problem;
}
}
One class, and every endpoint in the application inherits the same error
behavior. Add a new @ExceptionHandler method whenever you introduce a new
kind of failure worth distinguishing — you don't touch a single controller to
do it.
ProblemDetail: a shape you don't have to invent
That ProblemDetail type isn't a house-made DTO — it's part of Spring
(org.springframework.http.ProblemDetail), and it implements
RFC 7807 ("problem+json"), a real
IETF standard for API error bodies. It gives you type, title, status,
detail, and instance for free, plus setProperty for anything extra your
API needs — like the field-level errors list above. A validation failure
against CreateTaskRequest now comes back as something a client can actually
parse and act on:
{
"type": "about:blank",
"title": "Validation failed",
"status": 400,
"errors": [
{ "field": "title", "message": "title is required" },
{ "field": "dueDate", "message": "dueDate cannot be in the past" }
]
}
Compare that with a stack trace, and it's obvious which one a frontend developer — or a future you, six months from now — would rather receive.
Custom exceptions carry meaning
MethodArgumentNotValidException is thrown for you by the validation
machinery, but most of your own error cases need their own exception type.
Keep them small and specific:
public class TaskNotFoundException extends RuntimeException {
public TaskNotFoundException(Long id) {
super("No task with id " + id);
}
}
Then throw it from wherever the failure actually happens — usually the service layer, not the controller:
public Task getTask(Long id) {
return taskRepository.findById(id)
.orElseThrow(() -> new TaskNotFoundException(id));
}
The controller stays clean, the exception name documents intent at the call
site, and the @RestControllerAdvice decides — in exactly one place — which
HTTP status and body each exception type maps to.
Not leaking internals
The generic Exception handler above does two things worth calling out
separately, because it's easy to get only one of them right:
- Log the real thing, server-side.
log.error("Unhandled exception", ex)keeps the full stack trace in your logs, where you — and only you — can see it. - Return a generic message, client-side. The caller gets "An unexpected error occurred," not the exception's message, not a table name, not a file path. Internal errors are internal for a reason: a class name or SQL fragment in a 500 response is a small but free gift to anyone probing your API.
This is also why spring.jaeger.exposure and friends aside, you should
confirm your application.yml doesn't have
server.error.include-stacktrace: always left over from a debugging session.
The default (never) is the right value for anything that isn't your own
laptop.
Trying it end to end
With the DTO, the @Valid parameter, and the advice class in place, the same
bad request that used to produce a raw 500 now produces something usable:
curl -s -X POST localhost:8080/api/tasks \
-H "Content-Type: application/json" \
-d '{"title": "", "dueDate": "2020-01-01"}' | jq
returns a 400 with both violations listed by field, in one response, on the
first request — no guessing which field was wrong, no trial and error.
What's next
The API now rejects bad input with a message a client can use, and failures come back in one consistent shape instead of whatever the JVM felt like printing that day. That's the last piece needed before the project is worth trusting — which is exactly what Part 12: Testing Your Spring Boot Application is for: proving, with JUnit and Mockito, that both the happy path and these new failure paths actually behave the way this post claims they do.