AJAX error message on the ASP.NET forums

If you’ve done much ASP.NET AJAX development, you’re no doubt familiar with JavaScript alert errors similar to the one pictured above. This particular one occurs on the official ASP.NET forums in FireFox, if you try to navigate away from viewing a user profile before the Recommended Reading panels asynchronously load.

Not only is the error message of “…” completely meaningless, but it blocks your intended navigation away from the page until you’ve dismissed the alert window. Hopefully, someone at Telligent will read this, because the ASP.NET AJAX framework gives us an easy way to replace the annoying JavaScript alerts and vastly improve the usability of our applications.

Some “exceptional” code

First, we’ll need some code to throw exceptions to test with:

This throws a server side error when Button1 makes an asynchronous callback. If Button1 is clicked, we’ll get a JavaScript alert:

Error thrown by the test code

Handling the exception

The key to custom error handling in ASP.NET AJAX is the EndRequestEventArgs class, available when handling the endRequest event. It provides information on any error conditions that have resulted and exposes a method to let the framework know that we’ve handled the errors on our own.

I’m going to add a div, to serve as our replacement error message:

Next, some CSS to style the div and close button:

Finally, we need to add some JavaScript to tie it all together:

The crux of this method is EndRequestEventArgs.set_errorHandled(). This tells the AJAX framework to call off the dogs and prevents the JavaScript alert from being displayed. Now, clicking Button1 results in this:

Custom error handling example

We have complete control over the error display. No JavaScript alert!

Room for improvement

My example could certainly use some aesthetic improvement, but its usability is leaps and bounds ahead of a modal, JavaScript alert.

In actual implementation, I typically use jQuery to fade the error div in, slowly color fade to a more neutral color, and then fade it out after a moment. You could also do the same, using an AnimationExtender.

Additionally, the specific exception is provided in args.get_error().name. This should be leveraged to provide a more informative error message (perhaps, better than “…”).

The possibilities are nearly limitless. Remember that your users will eventually see these JavaScript alerts, no matter how robust your application is, even if just for timeout errors. Make sure to spend a few minutes to implement exception handling that won’t leave them scratching their heads.