Start learning free

LESSON 17 OF 173 · BACKEND: YOUR FIRST API

When It Isn't There in Java

Practice

When no product has the id that was asked for, the loop in getProduct ends without a match. Java checks every way through a method that returns a value, so something must come after the loop: without it, the code doesn't compile (missing return statement). Last lesson, that line was return ResponseEntity.status(404).build();: the right status, but an empty body.

The status code tells the client how its request went: 200 means OK, 404 means Not Found, 500 means the server failed. Returning a map sends 200. To send another status with a body, return a ResponseEntity: set its status, then its body. For example, a members-only page could answer 403, which means Forbidden:

@GetMapping("/vip")
Object vip() {
    return ResponseEntity.status(403).body(Map.of("error", "Members only"));
}

An API answers its errors in JSON too, like {"error": "Product not found"}, so the client's program can read what went wrong; Spring sends the map you put in .body(...) as JSON. The error belongs after the loop: those lines run only when no product matched. A path like /products/lamp never reaches your method: lamp can't become the int productId, so Spring itself answers 400 Bad Request.

Your app must answer:

GET /products/99    →  404  {"error": "Product not found"}
GET /products/2     →  200  {"id": 2, "name": "Notebook", "price": 7, "category": "office"}
GET /products/0     →  404  {"error": "Product not found"}
GET /products/5     →  404  {"error": "Product not found"}
GET /products/lamp  →  400  (an HTML error page)

Your task: after the loop in getProduct, make a Map<String, Object> named error with the key "error" and the value "Product not found", and return it as the body of a ResponseEntity with the status 404.


Assignment
Follow the Coding Tutorial to answer 404 with a JSON error when no product has the requested id.


Hint
The two new lines go after the loop, indented like the for line, not inside it. End the return with .body(error) instead of .build(): .build() sends an empty answer.


STEP 1 OF 2
    Ctrl + Enter to check

    Shop Not Found in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free