javascript - 扩展捕获原型以进行新遗物跟踪
问题描述
我想扩展 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);
解决方案
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)
推荐阅读
- javascript - 加/减数量按钮的问题
- bash - Cron 作业未运行 ssh
- django - Django Rest Framework:只需获取 ManyToMany 关系的某些值
- sql-server - 比较历史行(LAG 行)并将更改的值组合到单个列
- javascript - 如何在angularJS中创建对象数组
- javascript - 反应 onChange 事件未正确更新
- assembly - 使用 w3c Web 程序集 API 调用安装在计算机或设备上的本机程序集
- cucumber - 如何为每个测试用例生成黄瓜范围报告html
- sql - 在特定列中不重复查询,保留最新的
- javascript - 使用 javascript 按 ID 更改表单元素