Wednesday, 10 July 2019

Async Error Handling (try/catch)

I've been working on updating some of my older code to use async/await, and it's been going well, but I'm still uncertain around the best practices for error handling. I just read through this post - http://thecodebarbarian.com/async-await-error-handling-in-javascript.html and I think I get the idea, but wanted to double check.Here's a basic example:async function getData(database, queryString) { // Connect to database, run queryString, and get datas const datas = await connectToSomeDatabase(database, queryString); if (datas) return datas; } async function mailer(subject, message) { // Send an email to let me know that an error occurred await sendAnEmail(subject, message); } async function run() { try { const datas = await getData(var1, var2); if (datas === 'something') { // I've got data so I'll do something with it here } else { // I don't have data so I'm all done } } catch (error) { await mailer('Error!', 'Oops, there was an error, go check the logs.'); console.error(error.stack); } } run(); Is just having try/catch inside my run() function enough to capture any errors that occur in either getData or mailer? Or might some errors slip through the cracks?

Submitted July 10, 2019 at 06:46PM by knolll

No comments:

Post a Comment