2009-12-01 52 views
13

在我正在構建的ASP.NET Web應用程序中實現的UpdatePanel中出現異常時,它們會在頁面上導致JavaScript錯誤,並在警報中提供一些高級錯誤輸出。這對於開發來說是好的,但是一旦系統處於生產階段,由於多種原因顯然是不合適的。我可以圍繞Try Catch等麻煩的活動來控制Javascript錯誤,但在某些情況下,我想在主頁面上採取措施來支持用戶體驗。UpdatePanel異常處理

我該如何處理UpdatePanels中出現的錯誤,以提供無縫和無錯誤的Javascript實現?

回答

18

您可以使用上的ScriptManager(服務器端),並在PageRequestManager(客戶端)的EndRequest事件中使用的UpdatePanel時完全處理服務器端錯誤AsyncPostBackError事件的組合。

這裏有一些資源可以幫助你:

Customizing Error Handling for ASP.NET UpdatePanel Controls

Error Handling Customization for ASP.NET UpdatePanel

這裏有一個簡單的例子:

// Server-side 
protected void ScriptManager1_AsyncPostBackError(object sender, 
    AsyncPostBackErrorEventArgs e) { 
    ScriptManager1.AsyncPostBackErrorMessage = 
     "An error occurred during the request: " + 
     e.Exception.Message; 
} 


// Client-side 
<script type="text/javascript"> 
    function pageLoad() { 
    Sys.WebForms.PageRequestManager.getInstance(). 
     add_endRequest(onEndRequest); 
    } 

    function onEndRequest(sender, args) { 
    var lbl = document.getElementById("Label1"); 
    lbl.innerHTML = args.get_error().message; 
    args.set_errorHandled(true); 
    } 
</script> 
+0

謝謝你,非常感謝。 – Chris 2009-12-01 20:05:28

+0

在我修復了另一個相關問題後,這很好用:https://stackoverflow.com/questions/1671881/scriptmanager1-asyncpostbackerrormessage-not-showing-error-message – madamission 2018-02-19 00:37:24

0

您可以重寫頁面級錯誤方法,捕獲異常並處理您認爲合適的方式。

protected override void OnError(EventArgs e) 
{ 
    //show error message here 
} 
9

我這裏寫關於一個簡單的方法嗎這個: http://www.wagnerdanda.me/2010/01/asp-net-ajax-updatepanel-error-exception-handling-the-simple-way/

如果你只是想修復瀏覽器的JavaScript錯誤,並顯示異常信息給用戶,你只需要在窗體聲明後的某個地方本添加到您的母版:

<!-- This script must be placed after the form declaration --> 
<script type="text/javascript"> 
    Sys.Application.add_load(AppLoad); 

    function AppLoad() { 
     Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest); 
    } 

    function EndRequest(sender, args) { 
     // Check to see if there's an error on this request. 
     if (args.get_error() != undefined) { 

      var msg = args.get_error().message.replace("Sys.WebForms.PageRequestManagerServerErrorException: ", ""); 

      // Show the custom error. 
      // Here you can be creative and do whatever you want 
      // with the exception (i.e. call a modalpopup and show 
      // a nicer error window). I will simply use 'alert' 
      alert(msg); 

      // Let the framework know that the error is handled, 
      // so it doesn't throw the JavaScript alert. 
      args.set_errorHandled(true); 
     } 
    } 
</script> 

你並不需要捕獲OnAsyncPostBackError,即使除非要定製消息。 Go to my blog post if you want more information about this.

+0

工作!非常感激! – 2013-03-15 19:34:54