Asp.net Ajax Error Handling


This article is written by Pon Saravanan  on 02-Feb-10 Last modified on :22-Apr-10





Ajax Error Handling with ASP.net stack trace

ASP.Net Ajax is great for developing web applications. However there are some issues in displaying server side exceptions in the browser nicely. I actually needed the entire stack trace to be shown in the screen. Whenever I had an error while using Ajax, I used to get an alert with error message. Sometimes even I got notification in the status bar of the browser window. Instead of getting the error on the alert box, I wanted to get it on the body or label in the body of the browser window. Asp.net Ajax Error Handling support is already available, but using them is a bit not user friendly.

JavaScript to show error messages

Since the exception is passed to the browser from server side, we need a lot of Ajax Error Handling to do in the JavaScript. There are two events needs to be registered Begin Request and End Request in the Page Load event. PageLoad Event can be registered using Sys.Application.add_load (PageLoad) event. We need a label or DIV to display the error messages.

Register Events on PageLoad for Asp.net Ajax Error Handling

Two events needs to be registered BeginRequest, and EndRequest in the Page Load event using add_beginRequest and add_endRequest respectively

BeginRequest Event

Here we need to make the label invisible, because if there is no error no needs to display this label. Basically using a style to make it invisible will be sufficient.

EndRequest Event

 This is the main event to deal with the exceptions passed to the client. Here the invisible label will become visible. And the passed error description can be fetched using args.get_error ().description.

To display Stack Trace

With the above changes we can display the latest error message. To get the stack trace of the error from the server, we need to use the ScriptManager’s AsyncPostBackError event. The second argument contains the exception, so accessing and passing the stack trace is simpler. The modified error message can be passed to the client by assigning ScriptManager1.AsyncPostBackErrorMessage.
Finally you will be able to see the stack trace, but the information is not presented in a well readable format. The error message is not meant for the web, so the line breaks have to be replaced by <br />

Soure Code for Asp.net Ajax Error Handling

Markup (Aspx)

<%@ Page Language="VB" AutoEventWireup="false"
    CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="ErrorMessage" style="visibility: hidden;color:Red;">
        An error has occured while trying to process your request.
    </div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Label runat="server" ID="Label1"></asp:Label>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <hr />
    <asp:Button runat="server" ID="Button1" Text="Raise Error" />
    <asp:Button runat="server" ID="Button2" Text="No Errors" />
   
    <script type="text/javascript">
        Sys.Application.add_load(PageLoad);
        var ErrorMessage= document.getElementById('ErrorMessage');
        function PageLoad()
        {
            var AjaxSystem = Sys.WebForms.PageRequestManager.getInstance()
            AjaxSystem.add_beginRequest(BeginRequest);
            AjaxSystem.add_endRequest(EndRequest);
        }
        function BeginRequest(sender, args)
        {       
            if (ErrorMessage.style.visibility == "visible")
                ErrorMessage.style.visibility = "hidden";
        }
        function EndRequest(sender, args)
        {       
            if (args.get_error() != undefined)
            {
                ErrorMessage.style.visibility = "visible";
                ErrorMessage.innerHTML= args.get_error().description;
                args.set_errorHandled(true);
            }
        }   
   
    </script>
    </form>
</body>
</html>

 

Code-Behind(ASPX.VB)

Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) Handles Me.Load
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, _
                            ByVal e As System.EventArgs) Handles Button1.Click
        Throw New Exception("Sucess! Application Failed.")
    End Sub
    Protected Sub Button2_Click(ByVal sender As Object, _
                            ByVal e As System.EventArgs) Handles Button2.Click
    End Sub

    Protected Sub ScriptManager1_AsyncPostBackError(ByVal sender As Object, _
                            ByVal e As AsyncPostBackErrorEventArgs) _
                            Handles ScriptManager1.AsyncPostBackError
        ScriptManager1.AsyncPostBackErrorMessage = "<B>" & _
                e.Exception.Message & "</B><Br />" & _
                e.Exception.StackTrace.Replace(vbCrLf, "<br />")
    End Sub
End Class




« Previous -







Comments

Comments
   
Captcha Image
For you specially:  
Captcha Text Enter the text in the image.(Not Case sensitive)    



Spam Bot Trap



   



Select Theme
White
Blue
Brown
Gray