Sometimes the problem is not your request but the server. A status in the 500s, like 500 Internal Server Error, means your request was fine but the server failed while answering it: a bug, a database that is down, too much traffic. It isn't your fault, and the same request may work a minute later.
Worse than a 500 is no answer at all. By default fetch waits as long as the server takes. Pass { signal: AbortSignal.timeout(…) } as a second argument, with a number of milliseconds, to set a limit: when it runs out, fetch throws an error named TimeoutError. Catch it with try and catch, so your script carries on instead of crashing:
try {
const response = await fetch("https://api.example.com/weather", { signal: AbortSignal.timeout(5000) });
const data = await response.json();
console.log("Weather:", data.sky);
} catch (error) {
console.log("No weather today");
}
The supplier has a route for each problem: /broken always fails, and /slow takes 2 seconds to answer.
GET /broken → 500 {"error": "The supplier is down"}
GET /slow (1000 ms limit) → no answer after 1 second: fetch throws
Your script must print:
/broken: 500 The supplier failed: The supplier is down /slow: no answer after 1 second
Your task: inside main, fetch /broken and print its status, and for any status of 500 or more, the error from its JSON body. Then fetch /slow with a limit of 1000 milliseconds inside a try block: print its status if it answers in time, and a message if it times out.
Assignment
Follow the Coding Tutorial to handle a server error and a timeout without crashing.
Hintresponse.status >= 500 catches every server error at once. Inside the try block, the lines after the request run only when an answer came in time.
Free plan: 30 tutor messages. PRO is unlimited.
