30 Days Of JavaScript

Day 13: Async

Lesson 3: Catch

.then() isn't the only thing we can do with the result of a promise.

We talked about errors in day 9 and how we can use them in a try catch to gracefully handle errors. Well we can also catch errors with promises.

The request to the PokeAPI in this line:

1fetch('https://pokeapi.co/api/v2/pokemon/ditto)

Takes time because it has to travel across the internet. Traveling across the internet also means it is an unreliable request because, believe it or not, the internet is an unreliable place.

Requests and responses can have all sorts of problems cause them to fail.

If that request fails for any reason then we need a way to deal with that.

Enter .catch(), yep that's right, it has the same name as the catch from try/catch in day 9 except this time it's written in a way that we can chain it on to our promises.

Let's take a look at an example. You should notice what is wrong pretty quickly here, the url we are calling is very wrong 🤭

You should see "Failed to fetch" in you playground console. If you open up your developer tools console (Reminder below on how to do that) you will see a more informative error GET http://wrongaddressss.cool/ net::ERR_NAME_NOT_RESOLVED where ERR_NAME_NOT_RESOLVED means that there isn't a valid server at that web address to talk to, basically you dialled a wrong number.

To bring up the console in Chrome you can right click anywhere on the page and select Inspect. In the new area that pops up select Console, you'll see lots of logging and, hopefully at least one error message with Something went wrong in it.

Now, what's interesting about .catch() is that you only need one to catch all the errors in your full chain. Let's expand the example to try to access the JSON data from that bad address.

Notice how all you see in the playground console is Failed to fetch and nothing from (data) => console.log(data)? This is because, just like when we covered try/catch all the code after the error is skipped until a catch is hit.

Now look at this example:

You can see in this block of code:

1(data) => {
2  console.log(data);
3  throw new Error("Throwing an error for fun");
4};

I log out the data from the, now correct, PokeAPI but then I throw an error, just for fun. This is the show the the catch block will catch it - just like before, no matter where it is thrown from.

One catch block to rule them all.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co