陷阱 when.js 未处理的拒绝

trap when.js unhandled rejections

我想捕获 when.js 未处理的拒绝,以便我可以记录它们。为此,我覆盖了 console.warn(),但是它可以记录我不感兴趣的 when.js 以外的内容。

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

我正在使用 prettymonitor when.js https://github.com/AriaMinaei/pretty-monitor

如果您在服务器端,则可以使用承诺拒绝挂钩。这些将适用于服务器端的大多数承诺实现(io.js、bluebird、when 等):

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

如果您处于浏览器环境中,则标准化程度较低。但是,When 仍然在那里提供类似的钩子:

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

还有 local 拒绝挂钩,如果您只想处理对 promise 库的单个实例的拒绝,这些挂钩很好 - 这通常在构建库时很有用你自己:

var Promise = require('when').Promise;
Promise.onPotentiallyUnhandledRejection = function(rejection) {
    // handle single instance error here
};