• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

Ajax Error Handling with ASP.net stack trace ...

ASP.Net Ajax is great for developing web applications. However there are some issues in presenting 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. 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 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.
Coding is stupid!
Generate data entry and reporting .NET Web apps in minutes, straight from your database. Visually stunning, easy to customize and ready to deploy. Download Now!

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
Scrum Project Management - 1 User FREE
Get the tool that sprints as fast as your team. Burndown charts, sprint tracking, workflow, users and project manager dashboards. Free for 1 user. 30-day trials for teams. Download OnTime 2009 >>
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

 Original Source:
http://www.vbknowledgebase.com/?Id=126&Desc=Asp.net-Ajax-Error-Handling

AddThis Social Bookmark Button

Posted at 09:14:58 am | Permalink | Posted in .Net  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Top Stuff

e-messenger

MSN Web Messenger

eBuddy

ASP.NET Ajax CalendarExtender and Validation

AIM Express

Ajax Tools for ASP.NET Developers



About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Search


Topics

  • .Net (176)
  • Ajax (112)
  • Ajax Games (10)
  • Articles (95)
  • Bookmarking (35)
  • Calendar (21)
  • Chat (45)
  • ColdFusion (3)
  • CSS (84)
  • Email (23)
  • Facebook (84)
  • Flash (20)
  • Google (54)
  • Html (29)
  • Image (12)
  • International Calls & VOIP (7)
  • Java (58)
  • Javascript (280)
  • jQuery (200)
  • JSON (75)
  • Perl (2)
  • PHP (172)
  • Presentation (19)
  • Python (3)
  • Resources (2)
  • RSS (8)
  • Ruby (32)
  • Storage (4)
  • Toolkits (103)
  • Tutorials (227)
  • UI (11)
  • Utilities (174)
  • Web2.0 (18)
  • XmlHttpRequest (29)
  • YUI (13)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange