unhandledRejection event (Process)

Event: 'unhandledRejection'

Emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop. When programming with promises exceptions are encapsulated as rejected promises. Such promises can be caught and handled using promise.catch(...) and rejections are propagated through a promise chain. This event is useful for detecting and keeping track of promises that were rejected whose rejections were not handled yet. This event is emitted with the following arguments:

  • reason the object with which the promise was rejected (usually an Error instance).
  • p the promise that was rejected.

Here is an example that logs every unhandled rejection to the console

process.on('unhandledRejection', (reason, p) => {
    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
    // application specific logging, throwing an error, or other logic here
});

For example, here is a rejection that will trigger the 'unhandledRejection' event:

somePromise.then((res) => {
  return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)
}); // no `.catch` or `.then`

Here is an example of a coding pattern that will also trigger 'unhandledRejection':

function SomeResource() {
  // Initially set the loaded status to a rejected promise
  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
}

var resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn

In cases like this, you may not want to track the rejection as a developer error like you would for other 'unhandledRejection' events. To address this, you can either attach a dummy .catch(() => { }) handler to resource.loaded, preventing the 'unhandledRejection' event from being emitted, or you can use the 'rejectionHandled' event.

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

Please login to continue.