rejectionHandled event (Process)

Event: 'rejectionHandled'

Emitted whenever a Promise was rejected and an error handler was attached to it (for example with .catch()) later than after an event loop turn. This event is emitted with the following arguments:

  • p the promise that was previously emitted in an 'unhandledRejection' event, but which has now gained a rejection handler.

There is no notion of a top level for a promise chain at which rejections can always be handled. Being inherently asynchronous in nature, a promise rejection can be handled at a future point in time — possibly much later than the event loop turn it takes for the 'unhandledRejection' event to be emitted.

Another way of stating this is that, unlike in synchronous code where there is an ever-growing list of unhandled exceptions, with promises there is a growing-and-shrinking list of unhandled rejections. In synchronous code, the 'uncaughtException' event tells you when the list of unhandled exceptions grows. And in asynchronous code, the 'unhandledRejection' event tells you when the list of unhandled rejections grows, while the 'rejectionHandled' event tells you when the list of unhandled rejections shrinks.

For example using the rejection detection hooks in order to keep a map of all the rejected promise reasons at a given time:

const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, p) => {
  unhandledRejections.set(p, reason);
});
process.on('rejectionHandled', (p) => {
  unhandledRejections.delete(p);
});

This map will grow and shrink over time, reflecting rejections that start unhandled and then become handled. You could record the errors in some error log, either periodically (probably best for long-running programs, allowing you to clear the map, which in the case of a very buggy program could grow indefinitely) or upon process exit (more convenient for scripts).

doc_Nodejs
2016-04-30 04:42:04
Comments
Leave a Comment

Please login to continue.