Many failures of another service last only a moment: it restarts, or one of its servers hiccups, and the next request works. So before giving up, your shop can retry: ask again, a few times. It must also stop at some point, or a service that is really down would keep the customer waiting forever.
A retry is a while loop with a counter. Here a shop asks a news service at most 2 times:
int attempt = 1;
HttpResponse<String> reply = client.send(headlines, HttpResponse.BodyHandlers.ofString());
while (reply.statusCode() >= 500 && attempt < 2) {
attempt = attempt + 1;
reply = client.send(headlines, HttpResponse.BodyHandlers.ofString());
}
Only answers of 500 or more are worth another try: they are the other service's own trouble, and they often pass. A 404 stays a 404 however often you ask. A timeout is not retried either: a slow supplier has already cost the customer a second.
The checks make the supplier fail on purpose: POST /check/supplier-down with {"times": 2} makes its next 2 calls answer 500. Your shop must answer:
(the supplier will fail its next 2 calls)
GET /products/1/supplier-stock → 200 {"product_id": 1, "supplier_stock": 120}
(the supplier will fail its next 4 calls)
GET /products/3/supplier-stock → 502 {"error": "The supplier is not answering", "tries": 3}
GET /products/3/supplier-stock → 200 {"product_id": 3, "supplier_stock": 8}
GET /products/6/supplier-stock → 404 {"error": "The supplier doesn't sell this product"}
(the supplier will be slow once)
GET /products/1/supplier-stock → 504 {"error": "The supplier took too long"}
Your task: in supplierStock, call the supplier again while it answers 500 or more and fewer than 3 tries were made, count the calls in an int tries, and add "tries" to the 502 answer.
Assignment
Follow the Coding Tutorial to add retries, with a limit, to the supplier call in supplierStock.
Hint
The loop goes inside the try block, right below the first call. Join its two conditions with &&. Inside the loop, add 1 to tries and make the same call again. Declare tries above the try, starting at 1: the first call is try number 1.
Free plan: 30 tutor messages. PRO is unlimited.
