65.9K
CodeProject is changing. Read more.
Home

Handling Ajax Errors in ASP.NET

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

May 19, 2013

CPOL

1 min read

viewsIcon

12731

How to handle Ajax errors in ASP.NET

Introduction

Yesterday, I wrote about issue with Ajax postbacks in an application I am working currently. The problem was with buttons that was triggering UpdatePanels to update asynchronously. After adding loading indicator, I wanted to add error handling at client side.

As loading was handled by PageRequestManager events, I was trying to achieve errors in the same way. At first, I created some HTML to show when error happens:

<div id="errorDialog" class="hidden">
    <div class="ui-widget center height100per width100per">
        <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
            <p>
                <span class="ui-icon ui-icon-alert" style="float: left; 
                	margin-right: .3em;"></span>
                <strong>Error:</strong>
                <br />
                <span id="errorDesc"></span></p>
        </div>
    </div>
</div>

It creates Alert container from jQueryUI theme as you can see here. For me, it looks like this:

Styles are mostly from this library. My classes have meaningful names and are defined:

.width100per
{
    width:100%;
}
.height100per
{
    height:100%;
}

Folks at Microsoft do not add special event for errors in PageRequestManager, args argument of event handler for endRequest handler can tell as if something bad happened inside our application:

pageManager.add_endRequest(function (sender, args) {
        if (args.get_error() != undefined) {
                alert("Ouch!");
                alert(args.get_error().message);
        }
});

Now we have to just add some logic to show the error message inside our error container:

pageManager.add_endRequest(function (sender, args) {
        if (args.get_error() != undefined) {
            var errorMessage = args.get_error().message;
            args.set_errorHandled(true);
            jQuery('#errorDesc').html(htmlEncode(errorMessage).replace(":", "<br />"));
            jQuery('#errorDialog').dialog({
                width: 600,
                height: 300
            });
        }
        function htmlEncode(value) {
            return jQuery('<div/>').text(value).html();
        }
    });

htmlEncode function replaces special HTML characters like < or > with HTML entities. It works by creating in-memory-only div element, and then setting some HTML as text and getting this as HTML. Simple as that. I added replacing : with HTML next line to show error description from C# in the below summary of exception. After that dialog is opening to show to user that something bad happens.

Dialog is much bigger than it needs to be, but I think that user must know that it's something serious and bigger message helps with that. Smile

That's all!