首页 > 解决方案 > 扩展捕获原型以进行新遗物跟踪

问题描述

我想扩展 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);

标签: javascriptprototypees6-promisecatch-block

解决方案


to 的参数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调用都会给您带来一些误报(您实际上不想记录)以及误报(您应该已经捕获),因为错误处理程序是使用安装then的,或者根本没有catch调用。最好通过简单的可重用明确说明您希望将错误监控到哪里

function monitorError(error) {
    if (typeof newrelic !== 'undefined') {
        newrelic.noticeError(error);
    } else {
        console.error(error);
    }
}

您可以使用简单的方法显式注入或附加到 Promise 链中

.catch(monitorError)

推荐阅读