NovoGeek's Blog (Archive)

Technical insights of a web geek

Handling AJAX exceptions of ASP.NET using jQuery

Exception handling is an important feature in any business application. In simple words, it is all about catching ugly errors thrown by server and displaying them in a user friendly manner to the end user. (Of course, logging exceptions/notifications etc may also be a part of exception handling. )

ASP.NET provides API for handling exceptions and displaying them in custom error pages. Custom error pages can also be defined for different HTTP error status codes, which provides good experience to end users in case of exceptions.

However, if you are using AJAX in your ASP.NET application(I’m using jQuery library for AJAX), you would not like to redirect users to a custom error page, as that kills the primary motto of AJAX. You would instead like to display error messages in the same page, as in facebook or twitter. So here is how this can be done using jQuery:

jQuery’s $.ajax method has a special function, $.ajaxSetup, where global settings can be made for handling AJAX requests. If you use this global function, you need not write error callbacks for each of your AJAX requests. All erroneous AJAX requests will be handled by the global error callback in $.ajaxSetup function. We can take advantage of this and write our exception handling wrapper.

$.ajaxSetup({
    error: function(XHR, errStatus, errorThrown) {
 
        if (XHR.status == 0) {
            alert('You are offline!\n Please check your network.');
        } else if (XHR.status == 404) {
            alert('Requested URL not found.');
        } else if (XHR.status == 500) {
            var errorMessage = 'Internal server error';
            try {//Error handling for POST calls
                var err = JSON.parse(XHR.responseText);
                errorMessage = err.Message;
            }
            catch (ex) {//Error handling for GET calls
                $('#divMaster').append('<div id="divErrorResponse" class="DisplayNone">' + XHR.responseText + '</div>');
                errorMessage = 'Page load error: ';
                errorMessage += $('#divErrorResponse').find('h2 i').html();
            }
            alert(errorMessage);
        } else if (errStatus == 'parsererror') {
            alert('Error.\nParsing JSON Request failed.');
        } else if (errStatus == 'timeout') {
            alert('Request timed out..Please try later');
        } else {
            alert('Unknown Error.\n' + XHR.responseText);
        }
    }
});

In the above code, we are checking for status codes(which are self explanatory) and handling error conditions based on these codes. Most of the times, the status code will be “500”, which says “Internal Server Error”. i.e., error in your server side code. Please refer this article from Encosia.com, which explains the core of what I am writing now.

Now, this “500 – Internal Server Error” may arise in both GET as well as POST requests. In POST request, if your web method throws error, it returns a JSON object, which you can parse as explained in the above link. But this does not work in case of GET requests.

Assume that you are loading a remote page into a master page using jQuery AJAX. If your “Page_Load” event throws exception, your response would be in HTML format (unlike the case of POST request, where the response is JSON object), which you cannot parse using JSON.parse or eval(). To differentiate between GET & POST responses, I’m simply using JSON.parse() in try() method. If it throws exception, it is surely due to a GET response, which is html. For better user experience, you may use jGrowl plugin for displaying error messages.

Conclusion: For exceptions in GET requests, you can query the resultant html using jQuery’s DOM selectors and display user friendly messages. For exceptions in POST responses, you can simply parse the resultant JSON object and display user friendly messages. If you feel there could be a better way of handling exceptions in GET requests, let me know.

Hope this article saves the time of folks who are facing similar problems. Happy coding :)

Comments (1) -

  • utham

    1/10/2010 5:57:57 PM |

    This articale is really good and great.......kudos to krishna................this is what i have been looking and googling for a long time.........
    as I am implementing the JQuery Ajax Webservices.. i wanted to how to handle error msgs......but finally i found a very good code........
    thanks to Krishhhhhhhhh.........

    and pls suggest me a complete simplified Ajax Service code which contains all datafilter , errormsgs,success.beforeCallback.......to call services.......



Pingbacks and trackbacks (2)+

Comments are closed