A Lesson in Printing Errors within Try Catch Blocks
Hey there! π
Ever been stuck debugging an issue, only to find out it was something minor that could have been quickly resolved if only you had more information about the error?
Well, it happened to me today, and it inspired me to share this piece of wisdom: Always print the full error object when dealing with try-catch blocks in JavaScript.
Let's dive into it.
What Happened?
I was recently debugging an issue in my Node.js server. I was getting a confusing error message. The server was creating a playlist by fetching song IDs using a mocked YouTube API. However, for some reason, those songs were also failing to get their song IDs. The error message was always the same: "Error getting song ID". That's it.
The offending code looked something like this:
try {
song_id = await getSongID(song);
songs_with_ids.push({
id: song_id,
title: song,
});
} catch (e) {
console.log("Error getting song id for", song);
failed_songs.push({
id: null,
title: song,
});
}
The Lesson: Always Print Your Errors
I was confused. The function getSongID was mocked and supposed to return the song ID for all known songs, including the one causing the error.
After a moment of bewilderment, I decided to print the actual error object e in addition to my custom error message.
catch (e) {
console.log("Error getting song id for", song, "Error:", e);
failed_songs.push({
id: null,
title: song,
});
}
Boom! π₯ The error message changed to ReferenceError: song_id is not defined.
The issue wasn't with the getSongID function at all! Instead, it was an undeclared variable song_id that was causing the failure. This fixed it:
try {
const song_id = await getSongID(song);
songs_with_ids.push({
id: song_id,
title: song,
});
} catch (e) {
console.log("Error getting song id for", song);
failed_songs.push({
id: null,
title: song,
});
}
You can probably imagine the face-palm moment I had.
Takeaway
Writing custom error messages can certainly make your logs easier to read and understand. However, it's crucial to remember that these messages should augment the error object, not replace it.
By including the error object in your logs, you allow for the visibility of all the nitty-gritty details that come with an error: stack traces, line numbers, and the exact error message.
It's a simple practice, but one that can save you a lot of debugging time.
Stay curious, code more, and always print your errors!
I hope you found this post useful and it will save you from a few future headaches.
Happy coding! π
Top comments (0)