A service can also be slow instead of broken: overloaded, it answers after many seconds, or never. client.send waits as long as it takes, and so does your customer, while your shop keeps a worker busy for nothing.
Give the request a timeout: with .timeout(Duration.ofSeconds(1)) on the request builder, the HttpClient gives up after 1 second. Giving up throws an exception, HttpTimeoutException, which would crash the route. Catch it with try and catch: the catch block runs only when the code inside try threw that exception, and is skipped otherwise. Declare the response above the try, so the lines below the block can still use it. Here it is in a weather app:
HttpRequest request = HttpRequest.newBuilder(URI.create(WEATHER + "/today/" + name)).timeout(Duration.ofSeconds(2)).build();
HttpResponse<String> response;
try {
response = client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (HttpTimeoutException e) {
return ResponseEntity.status(504).body(Map.of("error", "The weather service took too long"));
}
The status is 504 Gateway Timeout: like 502, the problem is behind your shop, and 504 says exactly what it was. The customer waits one second at most, and gets an answer either way.
The check makes the supplier take 2 seconds for one request with POST /check/supplier-slow, 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-slow {"times": 1} → 200 {"slow_next": 1}
GET /products/1/supplier-stock → 504 {"error": "The supplier took too long"}
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, build the request with a 1-second timeout, declare response above a try block, send the request inside it, catch HttpTimeoutException, and answer "The supplier took too long" with 504. The 404 and 502 checks stay below, unchanged.
Assignment
Follow the Coding Tutorial to give the supplier call a time limit and answer 504 when it runs out.
HintHttpResponse<String> response; has no value yet; the line inside try sets it, without the type in front. The catch starts on the same line as the } that closes the try part.
Free plan: 30 tutor messages. PRO is unlimited.
