How to handle errors in Q in Node.js

There are times when rejection occurs with the promises creating errors. These errors are clever enough to dodge the handler assigned to take care of such errors. So, we need to take care of them explicitly.

Let's have a look at the following snippet and see how it can be handled:

return scenario().then(function (value) {
    throw new Error("I am your error mesg here .");
}, function (error) {
    // We only get here if scenario fails 
});

Why is this case happening? Suppose the parallelism between promises and try/catch and while we are trying to execute scenario(), the error handler represents a catch for scenario(), while the fulfillment handler represents code that happens after the try/catch block. Now, this code ...

Get Mastering JavaScript Promises now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.