Catch your errors
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.
onward-journeys module
Real. Simple. Syndication.
Get my latest content in your favorite RSS reader.
I use InoReader but you don't have to.
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).