Exception Handling in AJAX Using ASP.NET


Introduction 

AJAX (Asynchronous JavaScript and XML) is a new web development technique use for the interactive website. With AJAX help we can develop web applications and retrieve small amounts of data from a web server. AJAX is a different type of technology.

  • JavaScript
  • XML
  • Asynchronous Call to the server

Exception Handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions; special conditions that change the normal flow of program execution. Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and should, detect and handle program errors in your code. For example, validating user input, checking for null objects, and verifying the values returned from methods are what you expect, are all examples of good standard error handling that you should be doing all the time. When exceptions occur, they are said to be "thrown". Thrown is an object that is derived from the System. Exception class.

Namespace : Using System. Exception

The System. Exception class provides several methods and properties for obtaining information on what went wrong.

Try / Catch Blocks

When exceptions are thrown, you need to be able to handle them. This is done by implementing a Try/Catch block. Code that could throw an exception is put in the Try block and exception handling code goes in the catch block.

Finally Block

The finally block is useful for cleaning up any resources allocated in the Try block. Control is always passed to the finally block regardless of how the try block exits.

Step 1 : Open Visual Studio 2010.

  • Go to File->New->WebSite
  • Select ASP.NET Empty WebSite
step1.gif

Step 2 : Go to Solution Explorer and right-click.
  • Select Add->New Item
  • Select WebForm
  • Default.aspx page open
step2.gif

Step 3 :  Go to Default.aspx page and click on the [Design] option and drag control from Toolbox.

  • Drag ScriptManager control, UpdatePanel control, Label, Button
Define Content Template for UpdatePanel

Step 4 : Go to Default.aspx [Source] option and define <ContentTemplate> for the error message.

<ContentTemplate>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div id="divError" class="Error">
                <asp:Image ID="Image1" runat="server"
                    ImageUrl="~/ASP.jpg" ImageAlign="AbsMiddle" />
                Oooooops, <div id="divMessage" class="Message"></div>
            </div>
            <p>
                <asp:Button ID="Button2" runat="server"
                    Text="Create successful Ajax PostBack" OnClick="Button2_Click" />
                <asp:Button ID="Button1" runat="server"
                    Text="Create Exception!" OnClick="Button1_Click" />
            </p>
            <p>
                <asp:Label ID="lblDateTime" runat="server"></asp:Label>
            </p>
        </ContentTemplate>
    </asp:UpdatePanel
>

Handle Exception

Step 5 : We have two buttons inside the Update Panel. One that will perform a successful AJAX postback and render the current time, and one that will cause error.

Code :

<asp:Button ID="Button2" runat="server"
                    Text="Create successful Ajax PostBack" OnClick="Button2_Click" />
                <asp:Button ID="Button1" runat="server"
                    Text="Create Exception!" OnClick="Button1_Click" />
           

Handling Exception Using ScriptManger Control

Step 6 : Go to Default.aspx page [Design] option and click on ScriptManager Control.
  • Select Properties option and define OnAsyncPostBackError.
  • Write code.
Code

<form id="form1" runat="server" style="background-color: #BA5C45">
       <asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
/>
<div>

Step 7 : We will get the Exception message from AsyncPostBackErrorEventArgs class and pass it to the ScriptManager.

Create JavaScript Function

Step 8 :
First we will create pagerequstManager class and add a handler that will handle EndRequest event.  Next, we will proccess the arguments (EndRequestEventArgs class). We will  use get_error() property accessor method to determine if any error occurred.

JavaScript

<script type="text/javascript">
        function pageload() {
            var manager = Sys.WebForms.PageRequestManager.getInstance();
            manager.add_endRequest(onEndRequset);
        }
        function onEndRequest(sender, args) {
            if (args.get_error() != undefined) {
                $get('divMessage').innerHTML = args.get_error.message();
                $get('divEroor').style.display = "block";
            }
        }

Step 9 : Go to Default.aspx page option and write a code.

Code :

<title></title>
    <script type="text/javascript">
        function pageload() {
            var manager = Sys.WebForms.PageRequestManager.getInstance();
            manager.add_endRequest(onEndRequset);
        }
        function onEndRequest(sender, args) {
            if (args.get_error() != undefined) {
                $get('divMessage').innerHTML = args.get_error.message();
                $get('divEroor').style.display = "block";
                args.set_errorHandled(true);
       }   
    </script
>
</head>
<
body>
    <form id="form1" runat="server" style="background-color: #BA5C45">
       <asp:ScriptManager ID="ScriptManager1" runat="server" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
/>
<div>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div id="divError" class="Error">
                <asp:Image ID="Image1" runat="server"
                    ImageUrl="~/ASP.jpg" ImageAlign="AbsMiddle" />
                Oooooops, <div id="divMessage" class="Message"></div>
            </div>
            <p>
                <asp:Button ID="Button2" runat="server"
                    Text="Create successful Ajax PostBack" OnClick="Button2_Click" />
                <asp:Button ID="Button1" runat="server"
                    Text="Create Exception!" OnClick="Button1_Click" />
            </p>
            <p>
                <asp:Label ID="lblDateTime" runat="server"></asp:Label>
            </p>
        </ContentTemplate>
    </asp:UpdatePanel>
    </div>
    </form
>
</body>
</
html>

Step 10 : Go to Default.aspx.cs page and write a code.

Code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        throw new Exception("Exception generated on server occurred!");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        lblDateTime.Text = "The last Ajax PostBack occurred at " +
        DateTime.Now.ToString();
    }
    protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
    {
        ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message;
    }
}

Step 11 : Now run the application by Pressing F5.

exc.gif

Step 12 : When we click on the create Exception button then div (divError) that will display the Exception message.
 
exc2.gif

Step 13 : When we click on the Create Successful AJAX Post Back button display the last AJAX post back occurred with time.

exc1.gif

Up Next
    Ebook Download
    View all
    Learn
    View all