所以,如果你打开检查,你得到这个(如果你运气不好):控制台集成:获取抛出的错误/警告的数量?
我建立这显示调试信息的一个微小的JS组件 - 有什么办法读取到目前为止遇到的错误和警告的数量?
一个我可以想出的hacky解决方案通过用我自己的代替console.(error|log|warn)
函数涉及到一些诡计,但我还没有测试它是否适用于所有情况(例如我自己的代码之外)。
有没有更好的方法来做到这一点?
所以,如果你打开检查,你得到这个(如果你运气不好):控制台集成:获取抛出的错误/警告的数量?
我建立这显示调试信息的一个微小的JS组件 - 有什么办法读取到目前为止遇到的错误和警告的数量?
一个我可以想出的hacky解决方案通过用我自己的代替console.(error|log|warn)
函数涉及到一些诡计,但我还没有测试它是否适用于所有情况(例如我自己的代码之外)。
有没有更好的方法来做到这一点?
正如在this的答案中指出的那样,改变本地对象/方法的行为通常不是一个好主意。但是,下面的代码应该得到你在一个相当无害的方式所需要的:
// Add this IIFE to your codebase:
(() => {
\t // Get all of the property names of the console:
\t const methodsToTrack = Object.keys(window.console);
\t // Create an object to collect total usage tallies in:
\t const usageRegistry = {};
\t for (let i = 0, j = methodsToTrack.length; i < j; i++) {
\t \t let methodName = methodsToTrack[i];
\t \t // If the property is not a method, don't touch it:
\t \t if(typeof window.console[methodName] !== 'function') {
\t \t \t continue;
\t \t }
\t \t // Cache the original console method here:
\t \t let consoleMethod = window.console[methodName];
\t \t // Overwrite console's method to increment the counter:
\t \t window.console[methodName] = function() {
\t \t \t // Defining registry properties here, so the registry only contains values for methods that were accessed:
\t \t \t usageRegistry[methodName] = usageRegistry[methodName] || 0;
\t \t \t // Execute the original method's behavior, capturing the returned value (if any) in a var, to return it at the end:
\t \t \t const returnedValue = consoleMethod(...arguments);
\t \t \t // Increment the usage registry for the executed method:
\t \t \t usageRegistry[methodName]++;
\t \t \t // Return the value the console's method would have returned, so the new method has the same signature as the old.
\t \t \t return returnedValue;
\t \t };
\t }
\t // Define a funciton to output the totals to a console log, then clean up after itself:
\t window.showConsoleTallies = function() {
\t \t window.console.log(usageRegistry);
\t \t usageRegistry['log']--;
\t }
})();
// 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,如果你想它是编译用于旧版浏览器。
您需要在代码中使用某种包装来捕获未捕获的异常,或者需要以某种方式绑定到控制台API。 – ssube
您可以使用[devtools](https://developer.chrome.com/extensions/devtools)使用扩展名。 – mash
也许你可以使用window.onerror = function(msg,url,lineNo,columnNo,error) –