【问题标题】:Console integration: get number of errors/warnings thrown?控制台集成:获取抛出的错误/警告的数量?
【发布时间】:2016-06-17 15:06:11
【问题描述】:

所以如果你打开检查器,你会得到这个(如果你不走运的话):

我正在构建一个显示调试信息的微型 JS 组件 - 有没有办法读取到目前为止遇到的错误和警告的数量?

我可以提出的一个 hacky 解决方案涉及一些技巧,用我自己的替换 console.(error|log|warn) 函数,但我还没有测试它是否适用于所有情况(例如,在我拥有的代码之外)。

有没有更好的方法来做到这一点?

【问题讨论】:

  • 您需要某种类型的代码包装器来捕获其他未捕获的异常,或者您需要以某种方式绑定到控制台 API。
  • 您可以使用 chrome 扩展程序使用 devtools
  • 也许你可以使用 window.onerror = function (msg, url, lineNo, columnNo, error)
  • 我发现这篇文章可能有助于使用 window.onerror():danlimerick.wordpress.com/2014/01/18/…

标签: javascript google-chrome webkit frontend


【解决方案1】:

this 回答中所述,更改本机对象/方法的行为通常不是一个好主意。但是,以下代码应该以一种相当无害的方式为您提供所需的内容:

// Add this IIFE to your codebase:
(() => {
	// Get all of the property names of the console:
	const methodsToTrack = Object.keys(window.console);
	// Create an object to collect total usage tallies in:
	const usageRegistry = {};
	for (let i = 0, j = methodsToTrack.length; i < j; i++) {
		let methodName = methodsToTrack[i];
		// If the property is not a method, don't touch it:
		if(typeof window.console[methodName] !== 'function') {
			continue;
		}
		// Cache the original console method here:
		let consoleMethod = window.console[methodName];
		// Overwrite console's method to increment the counter:
		window.console[methodName] = function () {
			// Defining registry properties here, so the registry only contains values for methods that were accessed:
			usageRegistry[methodName] = usageRegistry[methodName] || 0;
			// Execute the original method's behavior, capturing the returned value (if any) in a var, to return it at the end:
			const returnedValue = consoleMethod(...arguments);
			// Increment the usage registry for the executed method:
			usageRegistry[methodName]++;
			// Return the value the console's method would have returned, so the new method has the same signature as the old.
			return returnedValue;
		};

	}
	// Define a funciton to output the totals to a console log, then clean up after itself:
	window.showConsoleTallies = function () {
		window.console.log(usageRegistry);
		usageRegistry['log']--;
	}
})();

// Examples:
showConsoleTallies();
console.log('log 1');
console.error('error 1');
console.log('log 2');
console.warn('warn 1');
console.error('error 2');
console.log('log 3');
showConsoleTallies();

PS:这是 ECMA6 版本,但如果您希望将其编译为在旧版浏览器中使用,请随时 run it through Babel

【讨论】:

  • 这会算 404 和 devtool 的计数器之类的异常吗?
  • 不幸的是,@dandavis,我认为它只会计算开发人员使用的控制台方法。 fetch('http://invalidajaxcall.com/').catch(showConsoleTallies)(例如)在后台似乎没有使用 console.error。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多