How to improve ASP.NET AJAX error handling
AJAX, ASP.NET, CSS, UI By Dave Ward on July 18th, 2007
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:
<asp:ScriptManager ID="sm1" runat="server" /> <asp:UpdatePanel runat="server" ID="up1"> <ContentTemplate> <asp:Button runat="server" ID="Button1" Text="Click Me" OnClick="Button1_OnClick" /> </ContentTemplate> </asp:UpdatePanel>
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:
<div id="Error" style="visibility: hidden;"> <img src="close.png" onclick="CloseError()" id="CloseButton" alt="Close Button" /> An error has occured while trying to process your request. </div>
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!
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.
Similar posts
What do you think? Your comments are welcomed.
I appreciate all of your comments, questions, and other feedback, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums. If you post there and then contact me with a link to the post, I'll try to take a look at it for you.
If you're replying to an existing comment, please use the threading feature. To do this, click the "Reply to this comment" link underneath the comment you're replying to.

Comments
I get an error message saying Sys is undefined when I try to do this. I am referencing the js file using ScriptManager. Everything else works on the site, including UpdatePanels. Any ideas what the issue might be?
When you reference script that interacts with the Sys namespace, as a ScriptManager include, you need to use an event handler to delay access of the PageRequestManager until after its available. If you put that JavaScript in an include file, replace the top two lines with this:
Thank you very much! That solved the issue.
hello,
I get the sys is not defined error still and still get the message box appear. The javascript is in the html page inbetween tags.
I dont know what I’m doing wrong?
Please help!
I’ve Fixed it!
Beautiful!
Thanks! This worked great, with one minor change to work in firefox: “args.get_error() != null” instead of “args.get_error != undefined”.
Out of curiosity, which version of FireFox are you using?
Thanks!! It works great. A good handy article. It worked with no problems in Firefox version 2.0.0.6
I had to also make the change to args.get_error()…
Strictly speaking, args.get_error should check for the existence of the function, whereas args.get_error() checks for a valid value *from* the function.
Two different things.
I’m curious which browser/version args.get_error didn’t work with. I tested in FireFox, IE, and Safari before posting.
However, I think you make a really good point about get_error() being better form. I changed the sample code to use the method explicitly.
Thanks for the input.
This solution doesn’t work in Firefox. I tried both inline and the include method. Works fine in IE for me. Am I missing something?
What version of FireFox are you using? The example screenshot above was taken in FireFox (it’s what I use 99% of the time and test with initially).
I apologize…actually it does work!
It will not work when framework throws exception as args.set_errorHandled(true); is written in endRequest handler.
You will get error messages in form of javascript alerts like Sys.InvalidIOperation: Could not find updatepanel with ID.
Below function of ajax library, will not show message when error is handled, but as code is written only in endrequest handler, error_handled flag is true and hence, you will get alerts.
function Sys$WebForms$PageRequestManager$_endPostBack(error, response) {
this._processingRequest = false;
this._request = null;
this._additionalInput = null;
var handler = this._get_eventHandlerList().getHandler(”endRequest”);
var errorHandled = false;
if (handler) {
var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, this._dataItems, response);
handler(this, eventArgs);
errorHandled = eventArgs.get_errorHandled();
}
this._dataItems = null;
if (error && !errorHandled) {
alert(error.message);
}
}
Your solution will only work when error created during postback, but not on cases when ajax framework throws invalid operation or parsing exceptions.
Can you please throw light on how to handle the ajax framework error as this solution wont handle it?
Hello,
Can you please write a post to compare POST and GET methods used in AJAX.
Also how we can handle ViewState when using Static Web Methods
Thank you
I have an ASP.NET AJAX page with several UpdatePanels. If error occured during asyncronous postback, I want to ignore it for some panels and show errors for other updatepanels.
My question is how can I find which of UpdatePanels caused the particular Request in EndRequestHandler?
In EndRequest, you can check sender._panelsToRefreshIDs. It’s a JavaScript array of UpdatePanel IDs being updated in the partial postback.
According to MS, there is a less javascript intensive way you can see here:
http://www.asp.net/AJAX/Documentation/Live/tutorials/CustomizingErrorHandlingforUpdatePanel.aspx
Thanks for the post.
Unless I’m missing something, the server side tutorial only goes as far as modifying the (still unfriendly) alert box’s message.
What this post is about is the next section of that page you linked, where the client side presentation is improved. They do it roughly the same way, at that point.
Hey
Thanks man followed this to the T and did some editing of my own and it worked brilliantly.
Kudos to a great article
hey, this code works beautifully.
but for those people who are working with masterpage (without the scriptmanager) and with only some page NOT implementing AJAX. It will cause some minor issues like
Sys is undefined.
Add a at the top of the page and replace
Sys.Application.add_load(AppLoad);
with the liner below.
if (Sys != null)
{
Sys.Application.add_load(AppLoad);
}
this will prevent non ajax page without scriptmanager from poping up the JS error
sorry for double post
i meant add a
at the top of the page
the script tag is not appearing.
Add a var Sys; at the top of the masterpage to prevent the error for non-ajax page from throwing JS error
You could also replace:
With: