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", so data.GetProperty("stock") throws, and the customer gets a 500 from your shop, 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:
var response = await http.GetAsync(WEATHER + "/today/" + name);
if ((int)response.StatusCode != 200) {
return Results.Json(new { error = "The weather service is not answering" }, statusCode: 502);
}
var data = await response.Content.ReadFromJsonAsync<JsonElement>();
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 the /products/{id}/supplier-stock route, below the 404 check, answer "The supplier is not answering" with 502 whenever the supplier's status 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 var data = .... Return Results.Json with statusCode: 502, like the 404 answer does with 404.
Free plan: 30 tutor messages. PRO is unlimited.
