Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle exceptions globally with native promises in node.js?

I know how to handle specific errors in promises but I sometimes have pieces of code that looks like this:

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

Sometimes, I get invalid JSON which causes a silent failure here when JSON.parse throws. In general 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 to find out where I forgot one.

How do I find these suppressed errors in my code?

like image 556
Benjamin Gruenbaum Avatar asked Feb 25 '15 01:02

Benjamin Gruenbaum


People also ask

How do you catch exceptions in promises?

catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.

Which of the following is the correct way to resolve unhandled exceptions in node JS?

Approach 1: Using try-catch block: We know that Node. js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can have try and catch block.

What steps must be taken when an uncaught in Promise error occurs in your console?

You only need to . catch this reject some where. ajax(request). catch(function(rejected){ console.


Video Answer


1 Answers

Edit

We've finally fixed this in Node.js 15, it took 5 years but native promise rejections now behave like uncaught exceptions - so it's fine to just add a process.on('uncaughtException' handler.

In Modern Node.js

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 puts an end to unhandled rejections problems and the difficulty of tracking them down in your code.

In Older NodeJS

These events were not yet back-ported to older versions of NodeJS and are unlikely to be. You can use a promise library that extends the native promise API such as bluebird which will fire the same events as there are in modern versions.


It's also worth mentioning that there are several userland promise libraries that offer the unhandled rejection detection facilities and much more such as bluebird (which also has warnings) and when.

like image 196
Benjamin Gruenbaum Avatar answered Oct 12 '22 14:10

Benjamin Gruenbaum