Skip to content
Gloved hand holding a baseball

Catch your errors

Monday, July 5, 2021

At 505 words, this article should take about 2 minutes to read.

All too often I have seen (and written) code that looks like this…

  const response = await getSomeDataFromAnAPI();
  handleTheHappyPath(response)

Invariably, at some point, the API is down or the response is malformed or my internet connection drops off or some other reason I haven't thought of and my handleTheHappyPath() function simply doesn't work.

Troubleshooting errors is tricky at the best of times but it's even harder if your code is not set up to handle errors.

Here are a few different ways to handle failures. Which one you should use will depend on a variety of things such as the existing codebase, when you want to handle the failure, or what you need to do in your handleTheHappyPath function.

Try/Catch

try {
  const response = await getSomeDataFromAnAPI();

  if (!response.ok || response.statusCode > 299) {
    throw new Error(response.statusText);
  }
  handleTheHappyPath(response)
} catch(error) {
  console.error('🚫  Oh noes!', error);
}

Then

  getSomeDataFromAnAPI()
  .then(response => {
    if (!response.ok || response.statusCode > 299) {
      throw new Error(response.statusText);
    }
    handleTheHappyPath(response)
  })
  .catch(error => {
    console.error('🚫  Oh noes!', error);
  })

Await

  const response = await getSomeDataFromAnAPI();
  handleTheHappyPath(response)

  response().catch((error) => {
    console.error('🚫  Oh noes!', error);
  })

Cover image courtesy of Diana Polekhina.

Comments

In almost all cases, the comments section is a cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on Twitter (which is, in it's own way, a vile cesspool of Reply Guys, racists, and bots).

Thomas Banks

Thomas Banks

When I'm not building things for the internet, I take photos of stuff.
Loading Invisible Visible Navigation Close Arrow Info Online Online