所以,如果你打開檢查,你得到這個(如果你運氣不好):控制檯集成:獲取拋出的錯誤/警告的數量?
我建立這顯示調試信息的一個微小的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) –