JQuery AJAX and Server side Exception Handling

I use PageMethods along with JQuery, a lot. However for exception handling, in the WebMethod, I put all the sensitive contents inside try-catch and call a custom Error function to log my errors. The problem is , I need to call my ErrorLogging function, for every static Webmethod, because the Application_Error handler in the global.asax, is totally ignored. I just pass some custom notification type of exception message to client. The raw exception generated in the WebMethod is logged & relevant system people are notified. The raw exception never hits the client.

However, in a similar JQuery-AJAX, if the server side code resides in an .ashx  handler, instead of PageMethod, — the global.asax as well as any custom error handling HttpModule works just fine – exactly similar to regular asp.net exception handling. So now, I have a centralized place to catch exception & no need to call the exception logging function everytime. Here’s an example which generates an exception , in the .ashx HttpHandler & Global.asax/Application_Error kicks in. On the client side , it’s a POST using JQuery $.ajax.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UsingExceptionModule2.aspx.cs" Inherits="UsingExceptionModule2" %>

<!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">
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" /> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 
    <script src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js" type="text/javascript"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js" type="text/javascript"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script> 

    <script type="text/javascript">
        $(document).ready(function () {

            $("#order1").click(function () {
                var Myname = "aaaaa";
                var Myemail = "bbbbb";
                var MyAddress = "ccccc";

                $.ajax({ type: "POST",
                    url: "Handler1.ashx",
                    data: 'Myname=' + Myname + '&Myemail=' + Myemail + '&MyAddress=' + MyAddress,
                    success: function (data) {
                        alert(data.d);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        debugger;
                    } 
                });
                
            });
        }); 
    </script> 


</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" id="order1" value="Raise Exception" /> 
    </div>
    </form>
</body>
</html>

Handler.ashx

<%@ WebHandler Language="C#" Class="Handler1" %>

using System;
using System.Web;

public class Handler1 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        var name = context.Request["Myname"];
        throw new Exception("aaaaaaaaaa");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

Global.asax

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs
        System.Web.HttpContext context = HttpContext.Current;
        System.Exception e123 = Context.Server.GetLastError();
        context.Server.ClearError();
        if (context.Request.CurrentExecutionFilePathExtension == ".ashx")
        {
            //LogMyError(e123); //Some custom logging mechanism...
            //Don't send the raw exception to client
        }
        else
        {
            Response.Redirect("SomeErrorPage.aspx");
        }
        
    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }
       
</script>

Advertisements
This entry was posted in JQuery and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s