Exception Handling With Update Panel in ASP.NET

If you don’t do anything, when you get an error during partial postback, you’ll get a simple alert message box showing you the error message associated with the exception you had in the server. As we all agree, this is not the best info to show to our users; it’s also not a good idea to show a standard error message. Suppose we don’t mind showing an alert message to the client. In that case, we can start by handling the AsyncPostBackError event generated by the ScriptManager control to customise the error message returned from the server. Here’s a simple page that shows this approach:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxErrorHandling.aspx.cs"  
Inherits="AjaxErrorHandling" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  
<html xmlns="http://www.w3.org/1999/xhtml" >  
<head runat="server">  
  <title>Untitled Page</title>  
</head>  
<body>  
  <form id="form1" runat="server">  
      <asp:ScriptManager runat="server" ID="manager"  
             OnAsyncPostBackError="HandleError">  
      </asp:ScriptManager>  
      <asp:UpdatePanel runat="server" ID="panel">  
          <ContentTemplate>  
             <asp:Button runat="server" ID="bt" Text="gerar erro no servidor"  
              OnClick="handleClick" />  
          </ContentTemplate>  
       </asp:UpdatePanel>  
       <div id="err"></div>  
  <!--Uncomment this for client side --->  
  <%--<script type="text/javascript">  
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest( endRequest );  
 function endRequest( sender, e ) {  
      if( e.get_error() ){  
             document.getElementById("err").innerText =  e.get_error().description;  
             e.set_errorHandled( true );  
      }  
 }  
  </script>--%>  
  
  
 </form>  
  
</body>  
</html>  
using System;  
using System.Data;  
using System.Configuration;  
using System.Collections;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  

public partial class AjaxErrorHandling : System.Web.UI.Page  
{  
 protected void Page_Load(object sender, EventArgs e)  
 {  

 }  
protected void handleClick(object sender, EventArgs e)  
 {  
     int a = 0;  
     int res = 10 / a;  
 }  
 protected void HandleError(object sender, AsyncPostBackErrorEventArgs e)  
 {  
     //here we could log the error, and see which exception we're getting in order to set a specific error message  
     //in this case, I'm just returning the current date/hour back   
     manager.AsyncPostBackErrorMessage = "Ooops...error occurred:  " +  
      DateTime.Now.ToString();  
 }  

}

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم