Skip to content
Gloved hand holding a baseball

Catch your errors

Monday, 5 July 2021

At 188 words, this article should take about 1 minute to read.

This article is more than a year old and the information in it may be out of date.

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.


Fin

Comments

In almost all cases, the comments section is a vile 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 Mastodon (which is not a vile cesspool of Reply Guys, racists, and bots).

Thomas Rigby

Thomas Rigby

When I'm not building things for the internet, I take photos of stuff.

Pronouns: he/him/his

Real. Simple. Syndication.

Get my latest content in your favorite RSS reader. I use InoReader but you don't have to.

What even is an RSS feed?!

Subscribe

Last played

Burn the Bitch

Ulver || Svidd Neger

Listen
Loading Invisible Visible RSS Navigation Close Arrow Info Online Online