JAVA-260 · Lesson 4 of 12 · 23 min

Request validation and error handling

▶ Video coming soon A video version of this lesson is on the way.

On Wednesday, February 2, Kofi came to the classroom with a printout. Over the weekend he had tried Hamza's development server from the counter computer and posted a booking with no name, a phone number of "asap" and a start time in 2019. The server had accepted it. Then he had asked for booking 99999 and got a page of Java stack trace. "Neither of those should happen when the public can reach it," Ingrid said. This lesson is about refusing bad input politely and reporting every kind of error in one consistent, documented format.

Never trust the request

Everything in a request comes from outside the service: the path, the query string, the headers and the body. A customer can make a typing mistake, a bug in the website can send the wrong field, and an attacker can send anything at all. The service must therefore check every value before acting on it. There are three layers. Syntax: is the body valid JSON and does each value have the right type? Spring and Jackson handle this and answer 400. Field rules: is the name present, is the phone number shaped like a phone number, is the start time in the future? Jakarta Bean Validation handles these with annotations. Business rules: is the shop open at that hour, is the slot still free? Those need the service's knowledge and live in the service.

Three layers of checking and the extra cases a service reports.
LayerExample failureWho checksStatus
SyntaxThe body is not JSON, or start is not a date-timeJackson and Spring MVC400 Bad Request
Field rulescustomer is blank, phone is "asap"Bean Validation on the request record400 Bad Request
Business rulesStart is on a Monday, when the shop is closedBookingService422 Unprocessable Content
Current stateThe slot has just been takenBookingService with the database409 Conflict
Missing resourceBooking 99999 does not existBookingService404 Not Found

Validating a record by hand

Bean Validation reads constraint annotations on fields or record components and reports every broken rule at once, so a client can fix all its mistakes in one go rather than one per request. The example builds the same idea from plain Java: a list of rules, each with a field name, a test and a message, run against a booking request. The fixed clock means the "in the future" rule gives the same answer every time the program runs.

Java Example · Main.java
import java.time.*;
import java.util.*;
import java.util.function.Predicate;

public class Main {
    record NewBooking(String customer, String phone, LocalDateTime start, String problem) {}
    record Rule(String field, Predicate<NewBooking> ok, String message) {}
    record Violation(String field, String message) {}

    static final Clock CLOCK = Clock.fixed(Instant.parse("2028-02-02T23:30:00Z"), ZoneId.of("America/Toronto"));

    static final List<Rule> RULES = List.of(
            new Rule("customer", b -> b.customer() != null && !b.customer().isBlank(), "must not be blank"),
            new Rule("phone", b -> b.phone() != null && b.phone().matches("\\d{3}-\\d{3}-\\d{4}"), "must look like 905-555-0142"),
            new Rule("start", b -> b.start() != null && b.start().isAfter(LocalDateTime.now(CLOCK)), "must be in the future"),
            new Rule("problem", b -> b.problem() == null || b.problem().length() <= 500, "must be at most 500 characters"));

    static List<Violation> validate(NewBooking b) {
        List<Violation> out = new ArrayList<>();
        for (Rule r : RULES) if (!r.ok().test(b)) out.add(new Violation(r.field(), r.message()));
        return out;
    }

    public static void main(String[] args) {
        NewBooking kofi = new NewBooking("", "asap", LocalDateTime.of(2019, 6, 1, 10, 0), "test");
        NewBooking good = new NewBooking("Ana Ferreira", "905-555-0142", LocalDateTime.of(2028, 5, 6, 10, 30), "Rear brake rubs");
        System.out.println("Kofi's test booking:");
        validate(kofi).forEach(v -> System.out.println("  " + v.field() + " " + v.message()));
        System.out.println("Ana's booking: " + (validate(good).isEmpty() ? "valid" : validate(good)));
    }
}
Output
Kofi's test booking:
  customer must not be blank
  phone must look like 905-555-0142
  start must be in the future
Ana's booking: valid

What this code does

Each rule is data: a field name, a predicate and a message, which is roughly what a constraint annotation carries. validate runs every rule and collects all the failures instead of stopping at the first, so Kofi's request reports three problems at once. The clock is fixed at an evening in February 2028, so a start time in 2019 is always in the past and the output never changes.

Bean Validation in Spring

Adding spring-boot-starter-validation brings Hibernate Validator, the reference implementation of Jakarta Validation. Constraint annotations go on the components of the request record, and @Valid on the controller parameter asks Spring to validate the body before calling the method. If any constraint fails, the method is not called at all: Spring throws a MethodArgumentNotValidException, and by default answers 400.

Java Example · NewBooking.java (needs Spring)
package org.secondgear.api.booking;

import jakarta.validation.constraints.*;
import java.time.LocalDateTime;

public record NewBooking(
        @NotBlank @Size(max = 80) String customer,
        @NotBlank @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}", message = "must have the form 555-555-0123") String phone,
        @Email String email,
        @NotNull @Future LocalDateTime start,
        @NotBlank @Size(max = 40) String bike,
        @Size(max = 500) String problem) {
}

What this code does

Each annotation is one rule: @NotBlank rejects null, empty and all-space text, @Size limits length, @Pattern checks a regular expression and @Future requires a time after now. The email is optional, but if it is present @Email checks its shape. Upper limits on every text field matter for security as well as tidiness, because they stop a client from sending a megabyte of text into a column meant for a name.

Java Example · The controller method with @Valid (needs Spring)
@PostMapping
ResponseEntity<BookingView> create(@Valid @RequestBody NewBooking request, UriComponentsBuilder uris) {
    BookingView created = bookings.book(request);
    return ResponseEntity.created(uris.path("/api/v1/repair-bookings/{id}").build(created.id())).body(created);
}

What this code does

@Valid in front of @RequestBody makes Spring run the record's constraints after Jackson has built it. If any fail, create never runs, so the service can assume its input has passed the field rules. @Validated on the class extends the same checks to @PathVariable and @RequestParam values.

Field rules belong on the request record, and business rules belong in the service. The record cannot know the shop's hours, which live in configuration, or whether a slot is free, which lives in the database. Spring Boot validates @ConfigurationProperties records the same way, which lesson 6 uses to stop the application starting with a nonsense setting.

A standard shape for errors: Problem Details

Before 2016, every API invented its own error body. RFC 7807 defined a standard JSON shape called Problem Details for HTTP APIs, and RFC 9457 replaced it in 2023 with small clarifications. A problem document has the media type application/problem+json and up to five standard members: type, a URI that identifies the kind of problem; title, a short human summary of that kind; status, the HTTP status code; detail, an explanation of this particular occurrence; and instance, a URI for this occurrence, often the request path. An API may add its own extension members, such as a list of field errors.

Java Example · Main.java
import java.util.*;

public class Main {
    record FieldError(String field, String message) {}

    record Problem(String type, String title, int status, String detail, String instance, List<FieldError> errors) {
        String json() {
            StringBuilder sb = new StringBuilder("{\n");
            sb.append("  \"type\": \"").append(type).append("\",\n");
            sb.append("  \"title\": \"").append(title).append("\",\n");
            sb.append("  \"status\": ").append(status).append(",\n");
            sb.append("  \"detail\": \"").append(detail).append("\",\n");
            sb.append("  \"instance\": \"").append(instance).append("\"");
            if (!errors.isEmpty()) {
                sb.append(",\n  \"errors\": [\n");
                for (int i = 0; i < errors.size(); i++) {
                    FieldError e = errors.get(i);
                    sb.append("    {\"field\": \"").append(e.field()).append("\", \"message\": \"").append(e.message()).append("\"}");
                    sb.append(i < errors.size() - 1 ? ",\n" : "\n");
                }
                sb.append("  ]");
            }
            return sb.append("\n}").toString();
        }
    }

    public static void main(String[] args) {
        Problem invalid = new Problem("https://api.secondgear.org/problems/invalid-booking", "Invalid booking request", 400,
                "2 fields are invalid", "/api/v1/repair-bookings",
                List.of(new FieldError("customer", "must not be blank"), new FieldError("start", "must be in the future")));
        Problem missing = new Problem("about:blank", "Not Found", 404,
                "No repair booking 99999", "/api/v1/repair-bookings/99999", List.of());
        System.out.println("Content-Type: application/problem+json");
        System.out.println(invalid.json());
        System.out.println(missing.json());
    }
}
Output
Content-Type: application/problem+json
{
  "type": "https://api.secondgear.org/problems/invalid-booking",
  "title": "Invalid booking request",
  "status": 400,
  "detail": "2 fields are invalid",
  "instance": "/api/v1/repair-bookings",
  "errors": [
    {"field": "customer", "message": "must not be blank"},
    {"field": "start", "message": "must be in the future"}
  ]
}
{
  "type": "about:blank",
  "title": "Not Found",
  "status": 404,
  "detail": "No repair booking 99999",
  "instance": "/api/v1/repair-bookings/99999"
}

What this code does

The record holds the five standard members plus an errors list, which is an extension member that this API documents for validation failures. The type URI names the kind of problem so that a client can recognize it in code, while title and detail are for people. The second problem uses about:blank as its type, which RFC 9457 defines as meaning that the problem is just the HTTP status, so its title is the status phrase.

Spring Framework has a ProblemDetail class with exactly these members and a setProperty method for extensions. Setting spring.mvc.problemdetails.enabled=true makes Spring MVC answer its own built-in errors, such as a malformed body or an unsupported media type, in this format. For your own exceptions you write a @RestControllerAdvice class: a bean whose @ExceptionHandler methods catch exceptions thrown by any controller and turn them into responses.

Java Example · ApiErrors.java (needs Spring)
package org.secondgear.api.web;

import java.net.URI;
import org.springframework.http.*;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

@RestControllerAdvice
class ApiErrors {
    private static final String BASE = "https://api.secondgear.org/problems/";

    @ExceptionHandler(BookingNotFound.class)
    ProblemDetail notFound(BookingNotFound e) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "No repair booking " + e.id());
    }

    @ExceptionHandler(SlotTaken.class)
    ProblemDetail slotTaken(SlotTaken e) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "The " + e.start() + " slot was just booked");
        p.setType(URI.create(BASE + "slot-taken"));
        p.setTitle("Slot no longer available");
        return p;
    }

    @ExceptionHandler(ShopClosed.class)
    ProblemDetail closed(ShopClosed e) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_CONTENT, e.getMessage());
        p.setType(URI.create(BASE + "shop-closed"));
        p.setTitle("The shop is closed then");
        return p;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail invalid(MethodArgumentNotValidException e) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST,
                e.getFieldErrorCount() + " fields are invalid");
        p.setType(URI.create(BASE + "invalid-booking"));
        p.setTitle("Invalid booking request");
        p.setProperty("errors", e.getFieldErrors().stream()
                .map(f -> new FieldProblem(f.getField(), f.getDefaultMessage())).toList());
        return p;
    }

    record FieldProblem(String field, String message) {}
}

What this code does

Each handler method catches one exception type thrown by any controller and returns a ProblemDetail, which Spring writes as application/problem+json with the status set inside it. The service throws meaningful exceptions such as SlotTaken and ShopClosed and never deals with HTTP itself. Spring fills in instance from the request path, and the validation handler adds the errors list as an extension property.

A request travels right from the client through four checkpoints in a row: JSON parsing, Bean Validation, the controller, and the service. From each checkpoint an arrow drops down to a single box marked RestControllerAdvice, which sends one application/problem+json response back to the client, with status 400, 400, 404 or 409 and 422 written beside the arrows.
Every failure, wherever it happens, leaves the service in the same Problem Details format.

From exceptions to status codes

The service layer speaks the language of the shop, not of HTTP. It throws BookingNotFound, SlotTaken or ShopClosed, and the advice class is the one place that decides which status each one becomes. The final example runs that arrangement end to end on the JDK's HttpServer: a tiny service throws domain exceptions, and a single handler wraps every request, catches them and answers with the right status and a problem document. Anything unexpected becomes a 500 with a generic message.

Java Example · Main.java
import com.sun.net.httpserver.*;
import java.net.*;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class Main {
    static class BookingNotFound extends RuntimeException { BookingNotFound(String m) { super(m); } }
    static class SlotTaken extends RuntimeException { SlotTaken(String m) { super(m); } }
    static class ShopClosed extends RuntimeException { ShopClosed(String m) { super(m); } }

    static final Map<Class<?>, Integer> STATUS = Map.of(
            BookingNotFound.class, 404, SlotTaken.class, 409, ShopClosed.class, 422);

    static String service(String path) {
        if (path.equals("/api/v1/repair-bookings/2041")) return "{\"id\":2041,\"status\":\"BOOKED\"}";
        if (path.startsWith("/api/v1/repair-bookings/")) throw new BookingNotFound("No repair booking " + path.substring(24));
        if (path.equals("/api/v1/book/2028-05-06T10:30")) throw new SlotTaken("The 2028-05-06T10:30 slot was just booked");
        if (path.equals("/api/v1/book/2028-05-08T10:30")) throw new ShopClosed("The shop is closed on Mondays");
        throw new IllegalStateException("database password rejected for user booking_app");
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/", ex -> {
            String path = ex.getRequestURI().getPath();
            int status = 200;
            String type = "application/json";
            String body;
            try {
                body = service(path);
            } catch (RuntimeException e) {
                Integer known = STATUS.get(e.getClass());
                status = known == null ? 500 : known;
                String detail = known == null ? "Something went wrong on our side" : e.getMessage();
                body = "{\"status\":" + status + ",\"detail\":\"" + detail + "\",\"instance\":\"" + path + "\"}";
                type = "application/problem+json";
            }
            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().add("Content-Type", type);
            ex.sendResponseHeaders(status, bytes.length);
            try (var out = ex.getResponseBody()) { out.write(bytes); }
        });
        server.start();
        try {
            HttpClient client = HttpClient.newHttpClient();
            String base = "http://127.0.0.1:" + server.getAddress().getPort();
            for (String p : List.of("/api/v1/repair-bookings/2041", "/api/v1/repair-bookings/99999",
                    "/api/v1/book/2028-05-06T10:30", "/api/v1/book/2028-05-08T10:30", "/api/v1/oops")) {
                HttpResponse<String> r = client.send(HttpRequest.newBuilder(URI.create(base + p)).build(),
                        HttpResponse.BodyHandlers.ofString());
                System.out.println(r.statusCode() + " " + r.headers().firstValue("Content-Type").orElse("") + " " + r.body());
            }
        } finally {
            server.stop(0);
        }
    }
}
Output
200 application/json {"id":2041,"status":"BOOKED"}
404 application/problem+json {"status":404,"detail":"No repair booking 99999","instance":"/api/v1/repair-bookings/99999"}
409 application/problem+json {"status":409,"detail":"The 2028-05-06T10:30 slot was just booked","instance":"/api/v1/book/2028-05-06T10:30"}
422 application/problem+json {"status":422,"detail":"The shop is closed on Mondays","instance":"/api/v1/book/2028-05-08T10:30"}
500 application/problem+json {"status":500,"detail":"Something went wrong on our side","instance":"/api/v1/oops"}

What this code does

The map from exception class to status code plays the part of the @ExceptionHandler methods: one place that knows how domain failures become HTTP. Known exceptions keep their message as the detail, because it was written for the customer. The unexpected IllegalStateException becomes a 500 whose detail is a generic sentence, so the database user name in its message never reaches the client.

That last line is the answer to Kofi's stack trace. An error response must never contain stack traces, SQL, file paths, class names or the text of an unexpected exception, because each is a clue for an attacker. Spring Boot's defaults already hide the stack trace (server.error.include-stacktrace is never by default). The full exception still goes into the service's log, with the request's path and a correlation ID, where the people running the service can find it; lesson 11 covers that.

Representative response (formatted)
curl -s -X POST http://localhost:8080/api/v1/repair-bookings \
  -H 'Content-Type: application/json' \
  -d '{"customer":"","phone":"asap","start":"2019-06-01T10:00","bike":"Trek FX 2"}'
Output
{
  "type": "https://api.secondgear.org/problems/invalid-booking",
  "title": "Invalid booking request",
  "status": 400,
  "detail": "3 fields are invalid",
  "instance": "/api/v1/repair-bookings",
  "errors": [
    {"field": "customer", "message": "must not be blank"},
    {"field": "phone", "message": "must have the form 555-555-0123"},
    {"field": "start", "message": "must be in the future"}
  ]
}

What this code does

This is Kofi's test request again, sent to the version with @Valid and the advice class. The response lists every invalid field in one problem document.

The order of the errors list is not guaranteed by Bean Validation, so a client should look entries up by field name rather than by position. The website will do exactly that: show each message under the matching form field.

Try it yourself

Validate the phone and the time

Complete validate so that it returns the list of problems for a booking, in this order of checks: customer must not be blank, phone must have the form 555-555-0123, and start must be between 09:00 and 15:00.

Return an empty list when everything is fine.

import java.time.*;
import java.util.*;

public class Main {
    record NewBooking(String customer, String phone, LocalTime start) {}

    static List<String> validate(NewBooking b) {
        List<String> problems = new ArrayList<>();
        return problems;
    }

    public static void main(String[] args) {
        System.out.println(validate(new NewBooking("Ana Ferreira", "555-555-0142", LocalTime.of(10, 30))));
        System.out.println(validate(new NewBooking(" ", "5555550142", LocalTime.of(16, 0))));
        System.out.println(validate(new NewBooking("Dev Okafor", "555-555-0199", LocalTime.of(8, 30))));
    }
}

Try it yourself

Build a problem document

Complete problem so that it returns a one-line JSON problem document with the members type, title, status, detail and instance, in that order.

For status 404 use the type about:blank and the title Not Found; for 409 use https://api.secondgear.org/problems/slot-taken and Slot no longer available.

public class Main {
    static String problem(int status, String detail, String instance) {
        return "{}";
    }

    public static void main(String[] args) {
        System.out.println(problem(404, "No repair booking 99999", "/api/v1/repair-bookings/99999"));
        System.out.println(problem(409, "The 10:30 slot was just booked", "/api/v1/repair-bookings"));
    }
}

Kofi tried his printout again the next morning and got three clear messages instead of a stored booking, then a tidy 404 instead of a stack trace. He pinned the problem document to the noticeboard by the counter with a note: "This is what good looks like."

Common mistakes

  • MistakeValidating only in the website's form.

    InsteadValidate on the server too; anyone can send a request without the website.

  • MistakeStopping at the first invalid field.

    InsteadReport every field error at once so the client can fix them together.

  • MistakePutting business rules in validation annotations.

    InsteadKeep field rules on the record and rules that need the shop's data in the service.

  • MistakeReturning stack traces or exception messages from unexpected errors.

    InsteadAnswer 500 with a generic detail and log the full exception on the server.

  • MistakeInventing a new error format for each endpoint.

    InsteadUse Problem Details (RFC 9457) everywhere, with documented type URIs and extension members.

Summary and key terms

  • Every value in a request comes from outside and must be checked.
  • Jackson and Spring reject malformed input with 400; Bean Validation annotations such as @NotBlank, @Size, @Pattern, @Email and @Future on request records check field rules when a parameter is marked @Valid; business rules live in the service and lead to 404, 409 or 422.
  • Problem Details (RFC 9457, replacing RFC 7807) gives errors a standard application/problem+json shape with type, title, status, detail and instance, plus documented extension members.
  • Spring's ProblemDetail class and a @RestControllerAdvice with @ExceptionHandler methods map domain exceptions to statuses in one place.
  • Unexpected errors become a 500 with a generic message, and the details go to the log, never to the client.
Bean Validation
The Jakarta standard for declaring field constraints with annotations; Hibernate Validator implements it.
@Valid
Asks Spring to validate an argument before calling the method.
Constraint
One rule on a value, such as @NotBlank or @Size(max = 80).
Problem Details
The RFC 9457 JSON format for HTTP API errors.
type (problem member)
A URI identifying the kind of problem; about:blank means just the HTTP status.
Extension member
An extra, documented field in a problem document, such as errors.
ProblemDetail
Spring's class representing a Problem Details document.
@RestControllerAdvice
A bean whose @ExceptionHandler methods handle exceptions from all controllers.
422 Unprocessable Content
A well-formed request that breaks a rule of the service.
409 Conflict
A request that clashes with the current state of the resource.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which annotation makes Spring validate a @RequestBody record?

    Show answer

    @Valid on the parameter.

  2. Name the five standard Problem Details members.

    Show answer

    type, title, status, detail and instance.

  3. Which RFC defines Problem Details today?

    Show answer

    RFC 9457, which replaced RFC 7807.

  4. Where should the rule "the shop is closed on Mondays" be checked?

    Show answer

    In the booking service, because it needs the shop's opening hours.

  5. What should a client see for an unexpected NullPointerException?

    Show answer

    A 500 problem document with a generic detail; the exception goes only to the log.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz