2012-01-25 25 views
0

我使用window.onerror,並window.onbeforeunload通過與AJAX的用戶會話遇到的所有錯誤,我想測試它,我需要創建一些JavaScript錯誤,以測試它是否是抓住它我嘗試過像var a = b這樣的東西; (其中B不存在)的問題是這些錯誤似乎是致命的,停止任何進一步的處理...是否有任何非致命的JavaScript錯誤,我可以用於測試..?

誰能想到一個體面的解決辦法會導致一些錯誤不停止腳本的處理?

ErrorManager: (function() { 
     function Init(message) { 
      InitErrorHandler(); 
      InitAjaxHandler(); 


     } 
     function InitErrorHandler() { 
      Data.ErrorHandlerText = ""; 
      Data.ErrorHandlerCount = 0; 
      window.onerror = function(errorMessage, url, line) { 
       Data.ErrorHandlerText +"Error: "+(Data.ErrorHandlerCount+1)+" \n\n"; 
       //Get error specific info 
       Data.ErrorHandlerText += escape(errorMessage) + "\n"; 
       Data.ErrorHandlerText += escape(url) + "\n"; 
       Data.ErrorHandlerText += escape(line) + "\n"; 
       Data.ErrorHandlerCount++; 
      } 
     } 
     function InitAjaxHandler() { 
      window.onbeforeunload = function() { //when browser closed 
       if(Data.ErrorHandlerCount > 0) { 
        SendErrorsToAjax(); 
       } 
      } 
     } 
     function SendErrorsToAjax() { 
      PrepareErrorsForAjax(); 
      $.getJSON(Interface.PrefixUrl('/sendjserrors/'+Data.ErrorHandlerText), AjaxCallback); 
     } 
     function AjaxCallback(response) { 
      console.log('response of js error ajax request '+response); 
     } 
     function PrepareErrorsForAjax() { 
      var preText = "A user has encountered a few errors: \n\n"; 
      //Get session info 
      var userAgent, activePageID; 
      userAgent = escape(navigator.userAgent); 
      preText += "User agent: "+userAgent+" \n"; 
      if($.mobile.activePage != null) { 
       activePageID = $.mobile.activePage.attr('id'); 
       preText += "Page ID: "+activePageID+" \n"; 
      } 

      preText += "\n The following errors were encountered:\n\n"; 
      Data.ErrorHandlerText = preText + Data.ErrorHandlerText; 
     } 
     return { 
      Init: Init, 
      SendErrorsToAjax: SendErrorsToAjax 
     } 
    })(), 
+0

你試圖把一個的console.log在window.onerror處理程序,看它是否甚至擊中:

您可以通過測試onerror的事情嗎? – SoWeLie

+0

沒有這種「致命的」錯誤。所有的錯誤都是相同的(堆棧溢出除外) – SLaks

回答

3

如何

throw new Error('No worries. Just testing...'); 

你必須趕上,雖然它,如果你不想讓你的程序中斷。

4

所有的錯誤在JavaScript中被認爲是致命的。當前碼塊(<script>標籤或外部文件)退出和頁面從</script>標籤起繼續進行。

我不知道一個try...catch塊是否會引發onerror,雖然。

1

謝謝你們,有你們說的話後圍繞一齣戲,因爲Kolink說,一旦出錯已經遇到過,劇本基本上退出這是遠遠不夠理想。

setTimeout("Interface.ErrorManager.SendErrorsToAjax()", 2000); 
var a = b; //create an error 
//script exists here, but the timeout still bounces in in a few seconds 
相關問題