

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Error Handling in TypeScript
incomplete
2: Bugs vs. Errors
incomplete
3: Async/Await Makes Error Handling Easier
incomplete
This lesson's interactive features are locked, please to keep using them
try and catch are the standard way to handle errors, the trouble is, the original Promise API with .then didn't allow us to make use of try and catch blocks.
Luckily, the async and await keywords do allow it, yet another reason to prefer the newer syntax.
The .catch() method works similarly to the .then() method, but it fires when a promise is rejected instead of resolved.
fetchUser()
.then((user: User) => {
console.log(`User fetched: ${user}`);
})
.catch((err: unknown) => {
if (err instanceof Error) {
console.log(`An error was thrown: ${err.message}`);
} else {
console.log("An unknown error occurred:", err);
}
});
try {
const user = await fetchUser();
console.log(`user fetched: ${user}`);
} catch (err) {
if (err instanceof Error) {
console.log(err.message);
} else {
console.log("An unexpected error occurred:", err);
}
}
As you can see, the async/await version looks just like normal try/catch TypeScript!
We're trying to fetch the worldwide leaderboard - users who have closed the most issues - from the Jello servers, but we're getting an error! Fortunately, it's just because the server is down, there's nothing wrong with the fetchLeaderBoard function.
However, as good software engineers, we need to handle our server being down cleanly and display an error message to our users.
Wrap the network call within a try/catch block. Within the catch block, don't worry about checking if it's an instance of an Error, just log the text:
Our servers are down, but we will be up and running soon