trap when.js unhandled rejections

2019-04-29 01:00发布

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

1条回答
Anthone
2楼-- · 2019-04-29 01:19

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
};
查看更多
登录 后发表回答