【发布时间】:2026-01-14 05:50:01
【问题描述】:
我在我的应用程序的 man 位置使用 console.error() console.warn() 来跟踪失败的代码。反正有没有自动将这些记录到哨兵。 https://sentry.io。
这是一个反应应用程序,他们建议的 componentDidCatch() 方法似乎只捕获异常。
【问题讨论】:
我在我的应用程序的 man 位置使用 console.error() console.warn() 来跟踪失败的代码。反正有没有自动将这些记录到哨兵。 https://sentry.io。
这是一个反应应用程序,他们建议的 componentDidCatch() 方法似乎只捕获异常。
【问题讨论】:
这样做的一种方法是用您自己的自定义实现覆盖console.error 和console.warn,因此每当代码的任何部分调用console.error 或console.warn 时,调用都会被您的自定义函数拦截您可以在其中对其执行所需的操作。
以下示例显示了console.error 方法的自定义实现。
//Store the original reference of console.error
var orgError = console.error;
//Overwirte the default function
console.error = function(error) {
//All error will be intercepted here
alert("Intercepted -> " + error);
//Invoke the original console.error to show the message in console
return orgError(error);
}
try {
//Following line will throw error
nonExistentFunction();
} catch (error) {
console.error(error);
}
【讨论】:
此问题的选定答案通常是反模式。您永远不想在浏览器中覆盖标准 API,因为您的应用程序中的其他代码实现可能期望该行为是一种特定的方式,并且可能会导致错误。此外,为您的代码库做出贡献的未来开发人员可能不会意识到您正在劫持标准并最终错误地使用它。
看看我专门为解决这些类型的问题而创建的一个开源项目:https://adzejs.com
使用 Adze,您可以创建日志侦听器,只要触发目标级别的特定日志,就会触发该日志侦听器。然后,您可以从侦听器向 Sentry 触发事件。
【讨论】: