At the end of the last lesson, countIfKnown() returned a Promise<number>, and the day’s total came out right because the species API was running. The API won’t always be there. A server goes down or a laptop loses its connection, and fetch() gets no reply at all. Then its promise rejects, and Node.js stops the import with TypeError: fetch failed.
In this lesson, you’ll catch that failure and read its message in a way the checker accepts. You’ll see why the caught value has the type unknown and how to narrow it. Start with the try...catch statement as you’d write it in plain JavaScript.
Catch a Failed Lookup
A failed lookup shouldn’t end the whole import, so the script should catch the rejection and report it. If the species API is running from an earlier lesson, go to its terminal and press Ctrl+C to stop it. Then create failed-lookup.ts in your millbrook-birders folder, with the lookup from the last lesson and one call inside a try block:
failed-lookup.ts
1type Sighting = { species: string; count: number };
2
3const API = "http://localhost:3000/species?name=";
4
5async function countIfKnown(sighting: Sighting): Promise<number> {
6 const response = await fetch(API + encodeURIComponent(sighting.species));
7 return response.ok ? sighting.count : 0;
8}
9
10const kite: Sighting = { species: "Red Kite", count: 2 };
11
12try {
13 console.log(`Red Kites: ${await countIfKnown(kite)}`);
14} catch (err) {
15 console.log(`Lookup failed: ${err.message}`);
16}
When the promise on line 13 rejects, await throws its reason, and the catch block receives it as err. Line 15 reads err.message, as you’ve done in JavaScript many times. Check the project: