How to improve ASP.NET AJAX error handling
AJAX, ASP.NET, CSS, UI By Dave Ward. Updated August 29, 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?
I appreciate all of your comments, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to another comment, use the threading feature by clicking "Reply to this comment" before submitting your own.



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!
how can I use an event handler to delay access on the PageRequestManager?
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:
Microsoft actually changed things for ASP.NET 3.5 and no javascript alert is displayed on the browser by default. You must now intercept the error manually.
This is not mentioned in ANY of the MSDN docs..
Have fun!!!
I noticed that, and am a bit ambivalent about the change. On the surface, it does get rid of the clunky alert windows, but it defaults your app to silently ignoring potentially important errors.
I suppose there’s a good argument that you should have an automated error logging process in place anyway, but it does seem like an easy pit to fall into.
Killer Code!!!
Thanks!!!
Hi This Sample is not working in asp.net2.0
when i click on the Button i am getting exception
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Exception: AJAX Error!
coudl you pls some one help me in this.
or can some one send me samle code how you guys did.
pls send the code on s726380@emirates.com
pls paste the code in the mail don’t attach the files
Thanks
Try running your program not in Debug mode (ctrl + F5)
Thousands thanks!!!
I use master pages and AJAX. I have been fighting against this AJAX silence upon postback errors for hours and hours! Now AJAX errors have colors and texts. Thanks to you! I use your code as followed …
Great work thanks a lot!
Also check this page out:
Customizing Error Handling for ASP.NET UpdatePanel Controls
…it demonstrates both methods, the ‘modal alert box’ method and the ‘div’ method.
Regards,
Anthony Walsh.
Great work! Thanks a lot!
Hello,
Kindly note that i am using the APPLICATION ERRO function to catch all unhandled errors. what is happening is that AJAX errors are now handled by the Application_Error.
Please advise how to handle AJAX errors alone.
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim vLastError As New Exception
vLastError = Server.GetLastError().GetBaseException()
If vLastError Is Nothing Then
Application(“GLOBAL_ErrorMessage”) = “No Errors”
Else
Application(“GLOBAL_ErrorMessage”) = vLastError.Message
End If
Server.ClearError()
Response.Redirect(“~/errors.aspx”)
‘Server.Transfer(“~/errors.aspx”)
End Sub
Im trying to get this to work with a masterpage.
I have a updatepanel on a content page and if I remove the updatepanel it works.
How do I solve this ?
That’s probably due to the rendered ClientIDs being changed in the Master/Content scenario. In my specific example, it shouldn’t matter since the div isn’t runat=”server”, but your situation may be impacted.
Try replacing any $get(‘ID’) with $get(‘< %= ID.ClientID %>‘) to make sure your JavaScript is referencing the correct element.
This is nice code and was fairly easy to adapt for use to masterpages, ajax, and Telerik controls. I used Telerik’s RadWindow alert box as the modal dialog – worked really slick. This good example saved me a few steps today.
John
Under some (my) conditions, when using args.get_error(), the error message is being cut due to some “undocumented” length limitations.
Any ideas how to increase the max message length of the AJAX error?
You may need to adjust maxJsonLength upward. See here for more info: http://msdn.microsoft.com/en-us/library/bb763183.aspx
Thanks Dave, that didn’t do the trick, but it leaded me the way to solve another error in our app…
Btw, are there any best practices or recommendations on how large to set the maxJsonLength?
As far as I know, there’s no detriment to setting it as high as you need. If you’re sending more than the default, you may want to consider breaking your data into pages or otherwise partitioning it though. It’s a good sign you may be dealing with too much data at once.
Thanks again, I will consider that.
The easy way:
where error is an object containing:
Hi ,
I have already used the
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
for different purpose at pagelevel i.e. for loading and closing progress bar.But now i got the new requirement.I need to hide All types of Ajax Errors and make the sesssion out.So if iam using the same above event,getting conflict.Is there any alternative to hide all the ajax errors.Its an urgent issue.Please help me as early as possible
I fought this problem for two days, until I found your post. You Rock!!! Thanks!
Testing for ‘undefined’ feels wrong here, as args.get_error() returns ‘null’ if there is no error (on my system anyway: ASP.NET 3.5 SP1). What’s wrong with the following test?
awesome work .!