We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Async/Await Makes Error Handling Easier

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.

.catch() Callback On Promises

The .catch() method works similarly to the .then() method, but it fires when a promise is rejected instead of resolved.

Example With .then and .catch Callbacks

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);
    }
  });

Example of Awaiting a Promise

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!

Assignment

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