Node.js: Promises and exceptions: a singularity

Promises in Node.js require an extra attention when it comes to what happens to exception handling.

Consider the following query with Mongoose:


users.findOne({lastname: 'Romanato'}).then(user => {

}).catch(err = > {
    // Detailed Mongoose error if query fails
});

In this case the error trapped within the catch block is returned by Mongoose and it is very detailed. Now consider another example:


users.findOne({lastname: 'Romanatoxyz'}).then(user => {
    // user might be null
    let email = user.email; // Oops!
}).catch(err = > {
    // Empty object {}
});

In this case instead the error trapped within the catch block is returned by the JavaScript interpreter and it is a simple empty object. In order to mitigate this problem you can use the async/await model which makes use of an explicit error handling through the traditional try/catch block. An even better solution would be to define your own exceptions.

Bear in mind that every evaluation of JavaScript expressions that may place within the then() block will be passed to the subsequent catch block if it raises an error.

Prev Articles Next