Start learning free

LESSON 26 OF 173 · BACKEND: YOUR FIRST API

One Way to Send Errors

Practice

Your shop sends errors from six places, and each one builds Map.of("error", ...) by hand. A client relies on every error having the same shape: it reads the message under the key "error". One typo in one place, like "eror", and the client loses that message.

The fix is a helper method: an ordinary static method, with no mapping annotation, that builds the answer in one place. It isn't a route; the routes call it and return what it gives them. It returns a ResponseEntity, which holds a body and a status together, and the route passes it on to Spring. A helper for success answers could look like this (not part of the shop):

static ResponseEntity<Object> created(Object item) {
    return ResponseEntity.status(201).body(item);
}

@PostMapping("/notes")
Object addNote(@RequestBody Map<String, Object> note) {
    notes.add(note);
    return created(note);
}

The answers stay exactly the same; only the code gets tidier. The requests and answers your code must give, in this order:

GET /products/9  →  404  {"error": "Product not found"}
POST /products  {"price": 5, "category": "kitchen"}
  →  400  {"error": "Name is required"}
POST /products  {"name": "Cup", "price": -1, "category": "kitchen"}
  →  400  {"error": "Price must be a whole number of 0 or more"}
DELETE /products/9  →  404  {"error": "Product not found"}
PUT /products/9  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  404  {"error": "Product not found"}
PATCH /products/9  {"price": 5}  →  404  {"error": "Product not found"}
POST /products  {"name": "Cup", "price": 5, "category": "kitchen"}
  →  201  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}
GET /products/5  →  200  {"id": 5, "name": "Cup", "price": 5, "category": "kitchen"}

Your task: write static ResponseEntity<Object> errorResponse(String message, int status), which returns the JSON body {"error": message} with the given status, and use it for every error answer in the shop: the 404 of getProduct, deleteProduct, updateProduct and patchProduct, and the two 400s of addProduct.


Assignment
Follow the Coding Tutorial to write the errorResponse helper and send every error through it.


Hint
The helper goes below the constructor, outside every route. In each route, write return errorResponse(...);. Until every route that can end without finding a product has that line, Java reports a missing return statement and the shop won't compile.


STEP 1 OF 8
    Ctrl + Enter to check