Handling Ajax errors in ASP.NET

Yesterday I wrote about issue with Ajax postbacks in application I am working currently. 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 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 http://jqueryui.com/themeroller/. For me it’s looks like this:

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

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

Folks at Microsoft does not added special event for handling errors in
PageRequestManager, but args argument of event endRequesthandler 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 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 charachters like < or > with HTML entities. It’s 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 below summary of exception. After that dialog is opening to show to user that something bad happens.

Dialog is much bigger then it needs to be but I think that user must know that it’s something serious and bigger message helps with that 🙂

That’s all!

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
14 + 12 =