Node.js Exception handling Errors and Promises

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Promises handle errors differently to synchronous or callback-driven code.

const p = new Promise(function (resolve, reject) {
    reject(new Error('Oops'));
});

// anything that is `reject`ed inside a promise will be available through catch
// while a promise is rejected, `.then` will not be called
p
    .then(() => {
        console.log("won't be called");
    })
    .catch(e => {
        console.log(e.message); // output: Oops
    })
    // once the error is caught, execution flow resumes
    .then(() => {
        console.log('hello!'); // output: hello!
    });

currently, errors thrown in a promise that are not caught results in the error being swallowed, which can make it difficult to track down the error. This can be solved using linting tools like eslint or by ensuring you always have a catch clause.

This behaviour is deprecated in node 8 in favour of terminating the node process.



Got any Node.js Question?