2010-06-21 133 views
1

有沒有什麼辦法可以捕捉到JavaScript中的任何未捕獲的異常?我的意思是,我所有的「危險」代碼都在try-catch塊中。但是,我不明確處理的異常呢?我使用jQuery,我主要的JavaScript文件開頭:jQuery異常處理

$(document).ready(function(){})

這裏我結合一些事件的一些DOM元素。我可以在這裏使用try-catch塊,但是它們會捕獲在事件綁定過程中發生的異常,而不是在事件處理期間發生。但是如果我在每個事件處理函數中都使用了try-catch塊,那將會很難看。

我應該如何捕獲在我的顯式try-catch塊中不存在的異常? (我不想寫通用處理函數,我只是想發送問題到我的服務器)

回答

4

你可以寫,將包你真正的處理程序在一個try/catch

function tc(func, msg) { 
    msg = msg || "Handler exception"; 
    return function(e) { 
    try { 
     return func(e); 
    } 
    catch (exc) { 
     $.post(/* send exception to server? */); 
     throw exc; // let nature take its course 
    } 
    }; 
} 

功能(可能想獲得參數處理等方面的專家)然後,當你綁定處理程序時,你會這樣做:

$('#whatever').click(tc(function(e) { 
    // your handler function 
}, "This is the message sent to the server when this handler fails")); 
+1

很酷的東西,我從來沒有使用例外。 – 2010-06-21 13:22:21

3

可以使用window.onerror事件處理程序,它不是歌劇,但並it may not fire in certain situations(感謝@Josh)的支持。

這樣做並不是真的明智,但是,它會讓bug找到一個噩夢的開始。通常最好先確保你的代碼沒有錯誤:-)你當然不需要在JavaScript中經常使用try... catch聲明,你肯定不應該使用空的catch塊。

我可以在這裏使用try-catch塊,但他們會抓住事件綁定過程中所發生,而不是在事件處理過程中的異常。

你也可以添加try/catch塊到內部範圍:

// Outer 
try { 
    $(document).ready(function(){}) 
} 
catch (e) { 
    /* Error handling */ 
} 

// Inner 
$(document).ready(function(){ 
    try { /* ... */ } catch (e) { /* Error handling */ } 
}); 
+1

此事件可能會或可能不會觸發,這取決於用戶代理配置。 – 2010-06-21 13:15:07

+0

更多這裏:http://stackoverflow.com/questions/1915812/window-onerror-does-not-work – 2010-06-21 13:17:31

+0

@Josh:謝謝你:-) – 2010-06-21 13:19:23

1

如何

function func_madness() { 
     throw("This function is throwing exceptions, because \n" + 
     "it can not throw polar bears and whales.\n"); 
    } // func_madness 

    window.onload = function() { 
     try { 
      func_madness(); 
     } catch (err) { 
      document.write("Caught it!\n<br/>\n" + err); 
     } // catch 
    } // window.onload 
+0

這真的讓我崩潰了! – aphoe 2016-08-24 17:41:07