How would you handle errors for async code in Node.js?

Technology CommunityCategory: Node.jsHow would you handle errors for async code in Node.js?
VietMX Staff asked 3 years ago

Handling async errors in callback style (error-first approach) is probably the fastest way to hell (a.k.a the pyramid of doom). It’s better to use a reputable promise library or async-await instead which enables a much more compact and familiar code syntax like try-catch.

Consider promises to catch errors:

doWork()
 .then(doWork)
 .then(doOtherWork)
 .then((result) => doWork)
 .catch((error) => {throw error;})
 .then(verify);

or using async/await:

async function check(req, res) {
    try {
        const a = await someOtherFunction();
        const b = await somethingElseFunction();
        res.send("result")
    } catch (error) {
        res.send(error.stack);
    }
}