Skip to content

Apologies for the appearance of the site. I'm designing in public!

Gloved hand holding a baseball

Catch your errors

Published on Monday, 5 July 2021.
At 186 words, this article should take about 1 minute 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);
})

Fin

Cover image courtesy of Diana Polekhina.

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).

onward-journeys module