trap when.js unhandled rejections

二次信任 提交于 2019-12-07 03:30:40

问题


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:


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
};


来源:https://stackoverflow.com/questions/29689143/trap-when-js-unhandled-rejections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!