How to handle exceptions globally with inline promises in node.js?

I know how to handle certain errors in promises , but I sometimes have code snippets that look like this:

somePromise.then(function(response){ otherAPI(JSON.parse(response)); }); 

Sometimes I get invalid JSON that causes a silent crash here when JSON.parse throw s. All in all, I have to remember to add a .catch handler to every single promise in my code, and when I don't, I have no way of knowing where I forgot it.

How to find these suppressed errors in my code?

+7
promise es6-promise
Feb 25 '15 at 1:38
source share
1 answer

In modern NodeJS

Starting with io.js 1.4 and Node 4.0.0, you can use the process "unhandledRejection" event:

 process.on("unhandledRejection", function(reason, p){ console.log("Unhandled", reason, p); // log all your errors, "unsuppressing" them. throw reason; // optional, in case you want to treat these as errors }); 

This will put an end to the raw failure problems and the difficulty of tracking them in your code.

In earlier versions of NodeJS

These events have not yet been ported to older versions of NodeJS and are unlikely to be so. You can use the promise library, which extends the promise compatibility API, for example bluebird , which will trigger the same events as in modern versions.




It is also worth noting that there are several user promise libraries that offer raw deviation detection tools and much more, such as bluebird (which also has warnings) and when .

+15
Feb 25 '15 at 1:38
source share



All Articles