为新遗物追踪扩展 catch 原型

Extending catch prototype for new relic tracking

我想扩展 Promise 对象的通用 catch 原型,以便在命中 catch 块时自动将错误记录到应用程序监控中。但是在尝试扩展捕获时,我无法从 Promise 对象中获取错误对象。

所以基本上不是在每个 then().catch() 中都这样做

axios.get('sample/url')
    .then(response => { stuff })
    .catch(error => {
        newrelic.noticeError(error);
    });

我想扩展 Promise 原型,但未能从中提取错误对象。

(function (Promise) {
    const originalCatch = Promise.prototype.catch;

    Promise.prototype.catch = function () {
        console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments);

        if (typeof newrelic !== 'undefined') {
            newrelic.noticeError(arguments[0]);
        } else {
            console.error(arguments);
        }

        return originalCatch.apply(this, arguments);
    };
})(Promise);

catch 的参数是回调函数,不是错误。

您正在寻找

Promise.prototype.catch = (function(originalCatch) {
    return function(onRejected) {
        console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments);
        return originalCatch.call(this, error => {
            if (typeof newrelic !== 'undefined') {
                newrelic.noticeError(error);
            } else {
                console.error(error);
            }
            return onRejected(error);
       });
    };
})(Promise.prototype.catch);

顺便说一句,我建议避免干扰 Promise.prototype。拦截每个 catch 调用会给你带来相当多的误报(你实际上不想记录)以及漏报(你应该捕获),因为错误处理程序是 installed using then 或没有catch 被调用了。最好通过简单的可重用

明确说明您希望错误去哪里进行监控
function monitorError(error) {
    if (typeof newrelic !== 'undefined') {
        newrelic.noticeError(error);
    } else {
        console.error(error);
    }
}

您可以使用简单的

显式注入或追加到 promise 链中
.catch(monitorError)

您可以通过 Promise 本身直接调用您的回调,以便评估参数:

(function (Promise) {
    const originalCatch = Promise.prototype.catch;

    Promise.prototype.catch = function () {
        console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments);

        if (typeof newrelic !== 'undefined') {
            originalCatch.apply(this, [newrelic.noticeError]);
               //^--- changed here.
        } else {
            console.error(arguments);
        }

        return originalCatch.apply(this, arguments);
    };
})(Promise);

示例工作代码:https://jsfiddle.net/7qgjr6fw/3/