Start learning free

LESSON 104 OF 173 · BACKEND: PAYMENTS AND OTHER SERVICES

When the Other API Fails

Practice

Other services break: a bug, a full disk, a deploy gone wrong. The supplier then answers 500 Internal Server Error, with JSON like {"error": "The supplier is down"}. That JSON has no "stock": data.get("stock") gives null, Map.of refuses a null value and throws, and the customer gets your shop's own 500 error page, as if your shop were broken.

Check the status before you trust the answer. Your route is a gateway: a server that passes requests on to another server. When the server behind it fails, a gateway answers 502 Bad Gateway. Here is the idea in a weather app:

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
    return ResponseEntity.status(502).body(Map.of("error", "The weather service is not answering"));
}
Map<String, Object> data = new ObjectMapper().readValue(response.body(), Map.class);

502 tells the client that the problem is behind your shop: not in its request (a 4xx), and not a crash of your shop (a 500). Keep the 404 check first, so the Teapot still gets its 404; then "not 200" catches every other failure.

The check switches the supplier off for one request with POST /check/supplier-down, a page that only exists in the tests. Your shop must answer:

GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/1/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/1/supplier-stock  →  200  {"product_id": 1, "supplier_stock": 120}
POST /check/supplier-down {"times": 1}  →  200  {"down_next": 1}
GET /products/3/supplier-stock  →  502  {"error": "The supplier is not answering"}
GET /products/6/supplier-stock  →  404  {"error": "The supplier doesn't sell this product"}

Your task: in supplierStock, below the 404 check, answer "The supplier is not answering" with 502 whenever response.statusCode() is not 200.


Assignment
Follow the Coding Tutorial to answer a clear 502 when the supplier fails, instead of crashing.


Hint
The new if goes between the 404 block and the data line. Return ResponseEntity.status(502).body(...), like the 404 answer does with 404.


STEP 1 OF 2
    Ctrl + Enter to check