Sunday, July 6, 2008

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:

protected void Button1_OnClick(object sender, EventArgs e)
{
throw new Exception("AJAX Error!");
}

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

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:

#Error {
top: 0px;
right: 0px;
width: 125px;
background-color: yellow;
border: solid 1px Black;
padding: 10px;
font-family: Sans-Serif;
font-size: 10pt;
position: absolute;
margin: 5px;
}
#CloseButton {
float: right;
cursor: pointer;
}

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

Sys.Application.add_load(AppLoad);

function AppLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
}

function BeginRequest(sender, args) {
// Clear the error if it's visible from a previous request.
if ($get('Error').style.visibility == "visible")
CloseError();
}

function EndRequest(sender, args) {
// Check to see if there's an error on this request.
if (args.get_error() != undefined)
{
// If there is, show the custom error.
$get('Error').style.visibility = "visible";

// Let the framework know that the error is handled,
// so it doesn't throw the JavaScript alert.
args.set_errorHandled(true);
}
}

function CloseError() {
// Hide the error div.
$get('Error').style.visibility = "hidden";
}

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:





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

source: encosia

0 comments: