Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trap when.js unhandled rejections

I'd like to trap when.js unhandled rejections so that I can log them. To accomplish this I've overriden console.warn(), however that can log stuff other than when.js which I'm not interested in.

ref: https://github.com/cujojs/when/blob/master/docs/api.md#debugging-promises

I am using prettymonitor with when.js https://github.com/AriaMinaei/pretty-monitor

like image 514
nevf Avatar asked Apr 17 '15 02:04

nevf


People also ask

How do you deal with unhandled rejection?

If an error condition arises inside a promise, you “reject” the promise by calling the reject() function with an error. To handle a promise rejection, you pass a callback to the catch() function. This is a simple example, so catching the rejection is trivial.

How do you terminate the node process in unhandled promise rejection?

To terminate the node process on unhandled promise rejection, use the CLI flag '--unhandled-rejections=strict' (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:89219) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.

What is unhandled promise rejection error?

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with . catch(). (rejection id: 1) (node:31851) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.

Why do Promises get rejected?

A Promise rejection indicates that something went wrong while executing a Promise or an async function. Rejections can occur in several situations: throwing inside an async function or a Promise executor/then/catch/finally callback, when calling the reject callback of an executor , or when calling Promise.


1 Answers

If you're on the server-side, you can use the promise rejection hooks. These will work on most promise implementations on the server-side (io.js, bluebird, when, etc):

 process.on("unhandledRejection", function(promise, reason){
    // deal with the rejection here.
 });

If you're in a browser environment, things are less standardised. However, When still provides similar hooks there:

window.addEventListener('unhandledRejection', function(event) {
    event.preventDefault(); // This stops the initial log.
    // handle event
    event.detail.reason; // rejection reason
    event.detail.key; // rejection promise key
}, false);

There are also local rejection hooks, these are good if you only want to handle rejections of a single instance of the promise library - this is typically useful for when building a library yourself:

var Promise = require('when').Promise;
Promise.onPotentiallyUnhandledRejection = function(rejection) {
    // handle single instance error here
};
like image 56
Benjamin Gruenbaum Avatar answered Oct 14 '22 17:10

Benjamin Gruenbaum