Skip to lesson

Returning the right status codes

A staff member adds a product whose SKU already exists, and the app still says "saved". The status code is the first thing a client reads: it decides whether to show the data, fix the request or try again later.

201 with Location, 200 and 204 for the CRUD operations

201 + Location is the answer to a POST that created a resource: status 201 Created, the new item in the body and a Location header with its absolute URL. A GET, PUT or PATCH answers 200 with the item; a DELETE answers 204 with no body.

Example 1 creates, reads, updates and deletes one category and shows the status of every call.

Example 1 · 201 + Location, 200, 204 and 404 for one category

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind 3.1.5)

CrudStatusDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicInteger;import java.util.regex.Matcher;import java.util.regex.Pattern;import tools.jackson.databind.json.JsonMapper;
record CategoryBody(String name, Integer parentId) {}
record Category(int id, String name, Integer parentId) {}
public class CrudStatusDemo {    static final JsonMapper JSON = JsonMapper.builder().build();    static final Map<Integer, Category> STORE = new ConcurrentHashMap<>();    static final AtomicInteger NEXT_ID = new AtomicInteger(8);    static final Pattern ONE = Pattern.compile("/api/v1/categories/([1-9][0-9]{0,8})");
    static void handle(HttpExchange exchange) throws IOException {        try (exchange) {            String method = exchange.getRequestMethod();            String path = exchange.getRequestURI().getPath();            Matcher m = ONE.matcher(path);            if (path.equals("/api/v1/categories") && method.equals("POST")) {                CategoryBody in = JSON.readValue(exchange.getRequestBody(), CategoryBody.class);                Category saved = new Category(NEXT_ID.getAndIncrement(), in.name(), in.parentId());                STORE.put(saved.id(), saved);                String host = exchange.getRequestHeaders().getFirst("Host");                exchange.getResponseHeaders().set("Location", "http://" + host + path + "/" + saved.id());                send(exchange, 201, saved);            } else if (m.matches()) {                int id = Integer.parseInt(m.group(1));                Category current = STORE.get(id);                if (current == null) {                    exchange.sendResponseHeaders(404, -1);                } else if (method.equals("GET")) {                    send(exchange, 200, current);                } else if (method.equals("PUT")) {                    CategoryBody in = JSON.readValue(exchange.getRequestBody(), CategoryBody.class);                    Category changed = new Category(id, in.name(), in.parentId());                    STORE.put(id, changed);                    send(exchange, 200, changed);                } else if (method.equals("DELETE")) {                    STORE.remove(id);                    exchange.sendResponseHeaders(204, -1);                }            } else {                exchange.sendResponseHeaders(404, -1);            }        }    }
    static void send(HttpExchange exchange, int status, Object value) throws IOException {        byte[] body = JSON.writeValueAsBytes(value);        exchange.getResponseHeaders().set("Content-Type", "application/json");        exchange.sendResponseHeaders(status, body.length);        try (OutputStream out = exchange.getResponseBody()) {            out.write(body);        }    }
    static void call(HttpClient client, String method, URI uri, String json) throws IOException, InterruptedException {        HttpRequest.Builder b = HttpRequest.newBuilder(uri).header("Content-Type", "application/json");        b.method(method, json == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(json));        HttpResponse<String> r = client.send(b.build(), HttpResponse.BodyHandlers.ofString());        String location = r.headers().firstValue("Location")                .map(l -> " Location: http://..." + l.substring(l.indexOf("/api/"))).orElse("");        System.out.println(method + " " + uri.getPath() + " -> " + r.statusCode() + location                + (r.body().isEmpty() ? "" : " " + r.body()));    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/api/v1/categories", CrudStatusDemo::handle);        server.start();        String base = "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/categories";        HttpClient client = HttpClient.newHttpClient();        try {            call(client, "POST", URI.create(base), "{\"name\":\"Stationery\",\"parentId\":null}");            call(client, "GET", URI.create(base + "/8"), null);            call(client, "PUT", URI.create(base + "/8"), "{\"name\":\"Office Supplies\",\"parentId\":null}");            call(client, "DELETE", URI.create(base + "/8"), null);            call(client, "DELETE", URI.create(base + "/8"), null);        } finally {            server.stop(0);        }    }}
Output
POST /api/v1/categories -> 201 Location: http://.../api/v1/categories/8 {"id":8,"name":"Stationery","parentId":null}
GET /api/v1/categories/8 -> 200 {"id":8,"name":"Stationery","parentId":null}
PUT /api/v1/categories/8 -> 200 {"id":8,"name":"Office Supplies","parentId":null}
DELETE /api/v1/categories/8 -> 204
DELETE /api/v1/categories/8 -> 404

What this code does

  • POST answers 201 with the new item and an absolute Location built from the Host header; the demo prints only its path because the port is random. GET and PUT answer 200 with the item.
  • DELETE answers 204 with -1 as the length: no body. The second DELETE finds nothing and answers 404, so the client can tell "deleted now" from "was never there".

A client can follow Location without knowing how your URLs are built, and a 204 tells it there is nothing to parse. Answering 200 with {"message":"created"} for everything forces every client to read your text to learn what happened.

The ShopLite server builds Location from the request: http:// + the Host header + the collection path + / + the new id. Deleting the same item a second time gets 404, because it no longer exists.

Predict the output

Which status?

Pick the status the server should send.

Round 1 of 3

A new category was saved. What does the POST answer?

POST /api/v1/categories
{"name":"Books"}

400 for malformed JSON or missing fields

validation-failed is a 400 Bad Request for a body that can be read but whose fields break rules; its errors array lists every broken field. A body that cannot be read at all (broken JSON, wrong type, unknown field) is malformed-request instead.

Example 2 sends an unreadable body, then a readable body with three broken fields.

Example 2 · malformed-request versus validation-failed

Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind 3.1.5)

BadRequestDemo.javaJava
import com.fasterxml.jackson.annotation.JsonInclude;import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.MapperFeature;import tools.jackson.databind.json.JsonMapper;
record ProductBody(String sku, String name, Integer categoryId, BigDecimal price) {}
record FieldError(String field, String message) {}
/** RFC 9457 Problem Details. errors is left out of the JSON when it is null. */record Problem(String type, String title, int status, String detail, String instance,               @JsonInclude(JsonInclude.Include.NON_NULL) List<FieldError> errors) {}
public class BadRequestDemo {    static final String TYPES = "https://shoplite.example/problems/";    static final JsonMapper JSON = JsonMapper.builder()            .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)            .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS)            .build();
    /** Every rule is checked; every broken field is reported, not just the first. */    static List<FieldError> validate(ProductBody p) {        List<FieldError> errors = new ArrayList<>();        if (p.sku() == null) {            errors.add(new FieldError("sku", "is required"));        } else if (!p.sku().trim().matches("[A-Z0-9-]{3,20}")) {            errors.add(new FieldError("sku", "must be 3-20 characters: A-Z, 0-9 or -"));        }        if (p.name() == null || p.name().trim().length() < 2 || p.name().trim().length() > 120) {            errors.add(new FieldError("name", "must be 2-120 characters"));        }        if (p.categoryId() == null) {            errors.add(new FieldError("categoryId", "is required"));        }        if (p.price() == null) {            errors.add(new FieldError("price", "is required"));        } else if (p.price().signum() <= 0) {            errors.add(new FieldError("price", "must be greater than 0"));        }        return errors;    }
    /** What POST /api/v1/products answers for a body: 201, or 400 of one of two kinds. */    static String handle(String body) {        ProductBody input;        try {            input = JSON.readValue(body, ProductBody.class);        } catch (JacksonException e) {                                   // cannot even read it            return JSON.writeValueAsString(new Problem(TYPES + "malformed-request", "Malformed request", 400,                    "The request body is not valid JSON.", "/api/v1/products", null));        }        List<FieldError> errors = validate(input);        if (!errors.isEmpty()) {                                         // readable, but breaks rules            return JSON.writeValueAsString(new Problem(TYPES + "validation-failed", "Validation failed", 400,                    "The request has " + errors.size() + " invalid fields.", "/api/v1/products", errors));        }        return "201 " + input;    }
    public static void main(String[] args) {        System.out.println(handle("{\"sku\":\"ACC-KB100\",\"name\":\"Zebronics Keyboard\",\"categoryId\":4,\"price\":999.00}"));        System.out.println(handle("{\"sku\":\"ACC-KB100\",\"name\":\"Zebronics Keyboard\""));        System.out.println(handle("{\"sku\":\"kb 1\",\"name\":\"K\",\"categoryId\":4,\"price\":-5.00}"));    }}
Output
201 ProductBody[sku=ACC-KB100, name=Zebronics Keyboard, categoryId=4, price=999.00]
{"type":"https://shoplite.example/problems/malformed-request","title":"Malformed request","status":400,"detail":"The request body is not valid JSON.","instance":"/api/v1/products"}
{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 3 invalid fields.","instance":"/api/v1/products","errors":[{"field":"sku","message":"must be 3-20 characters: A-Z, 0-9 or -"},{"field":"name","message":"must be 2-120 characters"},{"field":"price","message":"must be greater than 0"}]}

What this code does

  • A body that Jackson cannot read gets malformed-request; the client must fix the JSON itself. A readable body is then checked field by field.
  • All three broken fields come back in one validation-failed problem with an errors array. @JsonInclude(NON_NULL) leaves errors out of the other problem kinds.

400 Bad Request means the request itself is wrong and sending it again unchanged will fail again. A validation error lists every broken field, such as {"field":"price","message":"must be greater than 0"}, in the order the client sent them. Reporting only the first problem makes the user fix, resend and fail again, one field at a time.

Order matters on the server: parse first (malformed), then validate every field (validation-failed), and only then touch the database. Nothing is saved when any check fails.

Order of execution

What the server checks, in order

Put the steps in the order the server runs them.

404 and 409 from service-layer exceptions

409 / 422 are the answers for a readable request that a business rule refuses. 409 Conflict means it clashes with the current state (a used SKU, a category still in use). 422 means the fields refer to data that breaks a rule, such as an unknown categoryId.

Example 3 shows a service throwing exceptions and the caller turning them into 404 and 409.

Example 3 · Service exceptions become 404 and 409

ServiceErrorsDemo.javaJava
import java.util.Map;import java.util.TreeMap;
/** Service-layer exceptions: they describe what went wrong in business words, with no HTTP in them. */class NotFoundException extends RuntimeException {    NotFoundException(String message) {        super(message);    }}
class AlreadyExistsException extends RuntimeException {    AlreadyExistsException(String message) {        super(message);    }}
/** A tiny CatalogService: rules only, no HttpExchange, no status codes. */class CategoryService {    private final Map<Integer, String> names = new TreeMap<>(Map.of(1, "Electronics", 5, "Books"));
    String find(int id) {        String name = names.get(id);        if (name == null) {            throw new NotFoundException("Category " + id + " was not found.");        }        return name;    }
    int add(String name) {        if (names.values().stream().anyMatch(n -> n.equalsIgnoreCase(name))) {            throw new AlreadyExistsException("A category named " + name + " already exists.");        }        int id = names.size() + 7;        names.put(id, name);        return id;    }}
public class ServiceErrorsDemo {
    /** The HTTP layer decides the status: 404 for "not found", 409 for "clashes with what exists". */    static String call(Runnable work) {        try {            work.run();            return "2xx";        } catch (NotFoundException e) {            return "404 " + e.getMessage();        } catch (AlreadyExistsException e) {            return "409 " + e.getMessage();        }    }
    public static void main(String[] args) {        CategoryService service = new CategoryService();        System.out.println("GET  /categories/5       -> " + call(() -> service.find(5)));        System.out.println("GET  /categories/99      -> " + call(() -> service.find(99)));        System.out.println("POST {\"name\":\"Toys\"}    -> " + call(() -> service.add("Toys")));        System.out.println("POST {\"name\":\"books\"}   -> " + call(() -> service.add("books")));    }}
Output
GET  /categories/5       -> 2xx
GET  /categories/99      -> 404 Category 99 was not found.
POST {"name":"Toys"}    -> 2xx
POST {"name":"books"}   -> 409 A category named books already exists.

What this code does

  • CategoryService throws NotFoundException and AlreadyExistsException with messages for people; it knows nothing about HTTP.
  • The caller maps them: missing category 99 is 404, and books clashes with Books (names are unique ignoring case) so it is 409. Doing this in every handler is repetitive, which Example 5 fixes.

Services report outcomes with exceptions in business words, with no HTTP in them: NotFoundException ("Product 99 was not found."), AlreadyExistsException (a used SKU), InUseException (a category that still has products), RuleBrokenException (an unknown categoryId). The HTTP layer turns them into 404 (the resource in the URL does not exist), 409 and 422.

The same CatalogService also runs behind the console app and, later, Spring Boot. A service that returned 409 would be tied to HTTP; an AlreadyExistsException means the same thing everywhere.

The JDK sends HTTP/1.1 422 with no reason phrase, because its table of phrases has no entry for 422. Clients read the number, so this is harmless.

One catch-all: 500 with a safe Problem Details body

A catch-all is a try/catch (Exception e) around every handler that turns any unexpected exception into 500 Internal Server Error with a fixed, safe message, and writes the real cause to the server log.

Example 4 runs the same failing handler without and with a catch-all.

Example 4 · Without and with a catch-all

CatchAllDemo.javaJava
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;
/** Wraps any handler: an unexpected exception becomes a safe 500 and a log line, never a dropped connection. */class CatchAll implements HttpHandler {    private final HttpHandler next;
    CatchAll(HttpHandler next) {        this.next = next;    }
    @Override    public void handle(HttpExchange exchange) throws IOException {        try (exchange) {            try {                next.handle(exchange);            } catch (Exception e) {                // full detail for the developer, in the server log (stdout here, a log file in real apps)                System.out.println("  LOG ERROR " + exchange.getRequestMethod() + " " + exchange.getRequestURI()                        + " failed: " + e);                String json = "{\"type\":\"https://shoplite.example/problems/internal-error\","                        + "\"title\":\"Internal server error\",\"status\":500,"                        + "\"detail\":\"Something went wrong on our side. Please try again later.\"}";                byte[] body = json.getBytes(StandardCharsets.UTF_8);                exchange.getResponseHeaders().set("Content-Type", "application/problem+json");                exchange.sendResponseHeaders(500, body.length);                try (OutputStream out = exchange.getResponseBody()) {                    out.write(body);                }            }        }    }}
public class CatchAllDemo {
    /** A buggy handler: the report divides by the number of orders, which is 0 today. */    static void report(HttpExchange exchange) throws IOException {        int orders = 0;        int average = 19298 / orders;        exchange.sendResponseHeaders(200, -1);    }
    public static void main(String[] args) throws IOException, InterruptedException {        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);        server.createContext("/unsafe/report", CatchAllDemo::report);        server.createContext("/safe/report", new CatchAll(CatchAllDemo::report));        server.start();        String base = "http://127.0.0.1:" + server.getAddress().getPort();        HttpClient client = HttpClient.newHttpClient();        try {            for (String path : new String[] {"/unsafe/report", "/safe/report"}) {                System.out.println("GET " + path);                try {                    HttpResponse<String> r = client.send(HttpRequest.newBuilder(URI.create(base + path)).build(),                            HttpResponse.BodyHandlers.ofString());                    System.out.println("  client: " + r.statusCode() + " " + r.body());                } catch (IOException e) {                    System.out.println("  client: IOException: " + e.getMessage());                }            }        } finally {            server.stop(0);        }    }}
Output
GET /unsafe/report
  client: IOException: HTTP/1.1 header parser received no bytes
GET /safe/report
  LOG ERROR GET /safe/report failed: java.lang.ArithmeticException: / by zero
  client: 500 {"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"Something went wrong on our side. Please try again later."}

What this code does

  • The report handler divides by zero. On /unsafe/report the JDK drops the connection: the client gets an IOException and the server prints nothing.
  • CatchAll wraps the same handler: it logs the real ArithmeticException for the developer and sends 500 with a fixed Problem Details body that reveals nothing about the code.

Without it, the JDK closes the connection with no response and logs nothing: the client sees header parser received no bytes, and you have no clue. With it, the client gets a clear 500 it can show ("try again later"), and the developer gets the exception in the log.

Never put the exception text in the response. Messages like Unknown column 'p.prise' or a stack trace tell an attacker your table names and libraries. The contract allows only the generic detail for 500; the details stay on the server.

Find the bug

Find the unsafe line

Click the line that is wrong.

Which line leaks internal details to the client?

Round 1 of 2

Mapping exception types to status codes in one place

An error mapper is the one class that knows which exception means which status, type and title. Handlers let business exceptions fly, and the router's catch-all asks the mapper for the problem to send.

Example 5 maps every exception in one ErrorMapper. Example 6 shows the real ShopLite server answering curl.

Where each exception becomes a status. BadRequestException becomes 400. NotFoundException becomes 404. AlreadyExistsException and InUseException, both kinds of ConflictException, become 409. RuleBrokenException becomes 422.

Example 5 · One ErrorMapper for every exception

ErrorMapperDemo.javaJava
import java.util.List;
/** Business exceptions thrown by services (in ShopLite they live in com.shoplite.service). */class NotFoundException extends RuntimeException {    NotFoundException(String m) {        super(m);    }}
class ConflictException extends RuntimeException {    ConflictException(String m) {        super(m);    }}
class AlreadyExistsException extends ConflictException {    AlreadyExistsException(String m) {        super(m);    }}
class InUseException extends ConflictException {    InUseException(String m) {        super(m);    }}
class RuleBrokenException extends RuntimeException {    RuleBrokenException(String m) {        super(m);    }}
/** One row of the contract's error table. */record ProblemType(String slug, int status, String title) {}
record Problem(String type, String title, int status, String detail, String instance) {}
/** The ONE place that knows which exception means which status. Handlers just throw. */class ErrorMapper {    static final ProblemType NOT_FOUND = new ProblemType("not-found", 404, "Resource not found");    static final ProblemType ALREADY_EXISTS = new ProblemType("already-exists", 409, "Resource already exists");    static final ProblemType IN_USE = new ProblemType("in-use", 409, "Resource in use");    static final ProblemType INVALID_STATE = new ProblemType("invalid-state", 409, "Invalid state change");    static final ProblemType RULE_BROKEN = new ProblemType("rule-broken", 422, "Business rule broken");    static final ProblemType INTERNAL = new ProblemType("internal-error", 500, "Internal server error");
    Problem toProblem(Exception e, String path) {        ProblemType kind;        if (e instanceof NotFoundException) {            kind = NOT_FOUND;        } else if (e instanceof AlreadyExistsException) {            kind = ALREADY_EXISTS;        } else if (e instanceof InUseException) {            kind = IN_USE;        } else if (e instanceof ConflictException) {          // after its subclasses            kind = INVALID_STATE;        } else if (e instanceof RuleBrokenException) {            kind = RULE_BROKEN;        } else {            kind = INTERNAL;                                   // anything unexpected        }        String detail = kind == INTERNAL ? "Something went wrong on our side. Please try again later." : e.getMessage();        return new Problem("https://shoplite.example/problems/" + kind.slug(), kind.title(), kind.status(), detail, path);    }}
public class ErrorMapperDemo {    public static void main(String[] args) {        ErrorMapper mapper = new ErrorMapper();        List<Exception> errors = List.of(                new NotFoundException("Product 99 was not found."),                new AlreadyExistsException("A product with SKU MOB-RN13 already exists."),                new InUseException("Product 1 appears in orders and cannot be deleted."),                new ConflictException("Order 14 is SHIPPED and can no longer be cancelled."),                new RuleBrokenException("Category 42 does not exist."),                new IllegalStateException("pool exhausted: shoplite-pool, 5/5 in use"));        for (Exception e : errors) {            Problem p = mapper.toProblem(e, "/api/v1/products");            System.out.println(p.status() + " " + p.type().substring(p.type().lastIndexOf('/') + 1) + ": " + p.detail());        }    }}
Output
404 not-found: Product 99 was not found.
409 already-exists: A product with SKU MOB-RN13 already exists.
409 in-use: Product 1 appears in orders and cannot be deleted.
409 invalid-state: Order 14 is SHIPPED and can no longer be cancelled.
422 rule-broken: Category 42 does not exist.
500 internal-error: Something went wrong on our side. Please try again later.

What this code does

  • toProblem checks the subclasses AlreadyExistsException and InUseException before their parent ConflictException, so each conflict keeps its own type.
  • The unexpected IllegalStateException (its message mentions the connection pool) becomes 500 with the generic detail; the pool details never reach the client.

Example 6 · The ShopLite server answering with curl

Runs in: the shoplite-http project of this module, running on port 8080 with the seed data

Terminal
curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"MOB-RN13","name":"Another Redmi","categoryId":2,"price":999.00}'curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-MAT1","name":"Mouse Mat","categoryId":42,"price":199.00}'curl -i -X DELETE http://localhost:8080/api/v1/products/16curl -i -X DELETE http://localhost:8080/api/v1/products/16
Sample output
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
HTTP/1.1 201 Created
Date: Fri, 16 Oct 2026 06:26:53 GMT
Content-type: application/json
Content-length: 150
Location: http://localhost:8080/api/v1/products/16

{"id":16,"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"categoryName":"Accessories","price":999.00,"stock":30,"isActive":true}
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"MOB-RN13","name":"Another Redmi","categoryId":2,"price":999.00}'
HTTP/1.1 409 Conflict
Date: Fri, 16 Oct 2026 06:26:53 GMT
Content-type: application/problem+json
Content-length: 191

{"type":"https://shoplite.example/problems/already-exists","title":"Resource already exists","status":409,"detail":"A product with SKU MOB-RN13 already exists.","instance":"/api/v1/products"}
$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-MAT1","name":"Mouse Mat","categoryId":42,"price":199.00}'
HTTP/1.1 422 
Date: Fri, 16 Oct 2026 06:26:54 GMT
Content-type: application/problem+json
Content-length: 169

{"type":"https://shoplite.example/problems/rule-broken","title":"Business rule broken","status":422,"detail":"Category 42 does not exist.","instance":"/api/v1/products"}
$ curl -i -X DELETE http://localhost:8080/api/v1/products/16
HTTP/1.1 204 No Content
Date: Fri, 16 Oct 2026 06:26:54 GMT
$ curl -i -X DELETE http://localhost:8080/api/v1/products/16
HTTP/1.1 404 Not Found
Date: Fri, 16 Oct 2026 06:26:55 GMT
Content-type: application/problem+json
Content-length: 166

{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Product 16 was not found.","instance":"/api/v1/products/16"}

What this code does

  • The real ShopLite server uses the same mapper: 201 with an absolute Location, 409 already-exists for a used SKU, and 422 rule-broken for category 42. Errors use Content-type: application/problem+json.
  • The 422 status line has no reason phrase, as the JDK sends it. The first DELETE answers 204 with no body; the second finds nothing and answers 404.

With a try/catch in each handler, ten handlers soon give three different bodies for the same 404, and a new exception type means editing all of them. With one mapper, a new kind of error is one more line, and every endpoint answers in the same shape.

Check subclasses before their parent class: AlreadyExistsException and InUseException extend ConflictException, so testing ConflictException first would label every conflict invalid-state. Anything not in the list becomes 500 internal-error.

Next step

Check your understanding

12 quick questions