我希望能夠發送一個頁面上的所有javascript錯誤。我是一個擴展開發人員,所以下面的重點是確保在調用dom之前準備好dom。獲取頁面上的所有javascript錯誤/ javascript錯誤處理
我調查了爲throw
添加一些功能來發送或郵寄異常,但我沒有發現這是可能的。
1:主要解決了這一點,window.onerror處理:
window.onerror = function(e, url, line){
mailError('onerror: ' + e + ' URL:' + url + ' Line:' + line);
console.error('\nLine ' + line + ':');
setTimeout(function(){retry();}, 100); //mainly useful in content scripts for extensions,
return true;
}
可能還需要通過jQuery做同樣的事情:
$(window).error(
function(e, url, line){
//handle error
}
);
這樣做的垮臺是你的代碼已停止執行。
爲了避免錯誤停止執行,最好使用回調來確保代碼以特定順序執行,並儘可能地利用事件。您也可以保護DOM調用與
$(document).ready({
//you usually won't get bad dom calls wrapping your code in this
});
您也可以考慮在window.onload
window.onload = function(){
//you page will probably twitch upon executing code at this time
//but you will almost never have a bad dom call
};
另一種技術
if (document.getElementById('iNeedThisElement')) {
//doin work!
document.getElementById('iNeedThisElement').style.display = 'block';
} else {
var stillNeedToTakeCareOfX = true; //false otherwise since it's undefined
mailError('iNeedThisElement was unavailable...');
}
運行代碼中使用這些技術的一些技巧,只是調試應用程序,你應該相當順利。由於console.error,.warn,和.log語句不能被檢索並報告給你的,一個小的替代套件提供如下:
var Xe = { }; //Extreme error suite
function extraInfo(e){
//e optional
if(!e)e = true;
//add an extra debug info, such as navigator or current URL
return ' currentURL: '+ document.URL +
'\n userAgent: ' + navigator.userAgent +
'\n platform: ' + navigator.platform +
'\n userid: ' + localStorage.userid +
'\n language: ' + navigator.langauge +
'\n cookies?: ' + navigator.cookiesEnabled;
}
Xe.error = function(e){
console.error(e); //maintain original functionality
mailError('Xe err: ' + e + extraInfo());
}
Xe.warn = function(e){
console.warn(e);
mailError('Xe warn: ' + e + extraInfo());
}
Xe.log = function(e){
console.log(e);
mailError('Xe log: ' + e + extraInfo());
}
作爲最後一搏,你可以不斷嘗試執行的一大塊代碼直到執行沒有錯誤。這是下面的「2」。
2:在大塊組代碼,並試圖以後捕獲錯誤後重新執行x秒,或繼續的代碼下一個塊
//defExe = DEFinitely EXEcute this code
//functionArg, reference to a function holding a large chunk of code
//seconds, timeout in milliseconds to re-attempt error free execution of this function
function defExe(functionArg, seconds) {
//seconds is optional
if (!seconds)seconds = 300;
try {
functionArg();
} catch(e) {
//mail the error plus extra info
mailError('caught ' + e + ' attempting to re-execute ' + functionArg.name + ' in ' + seconds + ' milliseconds');
//re-attempt to execute this code
setTimeout(function(){
defExe(functionArg, seconds);
}, seconds);
}
}
此它然後被用於像
//array to group function chunks
var fn = [ ];
fn[1] = function(){
//a large chunk of javascript
}
defExe(fn[1]);
fn[2] = function(){
//another chunk of your program
}
defExe(fn[2]);
#2摘要:組函數中的代碼並在try-catch塊中運行,如果發生錯誤,則重複執行
你知道'fn.1'是無效的synthax?你需要使用'fn [1]'。 – HoLyVieR
所以實際上我想我已經發現我想要做的是使用YUI可用事件,當「DOM響應getElementById」時觸發http://developer.yahoo.com/yui/3/event/#onavailable 現在我只需要製作一個更精通的doc.byId函數,它可以在此YUI代碼功能中封裝dom調用。但是,我可能會失去一個錯誤,從而無法找出尚未運行的代碼。 –