UpdatePanel: having fun with errors

Published Sun, Oct 29 2006 15:52

UpdatePanel has always given us some sort of error handling during partial postbacks (or, if you want to use the new official term, async postbacks). In previous CTPs, you could handle a page error event and perform your own error handling (which normally consisted in some form of logging). The problem previous versions had was related with the way that the error message was shown in the client side (by default, it showed an alert message box, though you could define a limited error template). The current release give us a lot more options as I'll show you in this post.

If you don't do anything, when you get an error during partial postback you'll get a simple alert message box showing you the error message associated with the exception you had in the server. As we all agree, this is not the best info to show to our users; it's also not a good idea to show a standard error message. If we don't mind showing an alert message in the client, then we can start by handling the AsyncPostBackError event generated by the ScriptManager control in order to customize the error message returned from the server. Here's a simple page that shows this approach:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void handleClick(object sender, EventArgs e)
{
   int a = 0;
    int res = 10 / a;
}
void HandleError(object sender, AsyncPostBackErrorEventArgs e)
{
    //here we could log the error, and see which exception we're getting in order to set a specific error message
    //in this case, I'm just returning the current date/hour back
    manager.AsyncPostBackErrorMessage = "Ooops...error occurred:  " +
     DateTime.Now.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
   <head runat="server">
     <title>Untitled Page</title>
    </head>
<body>
  <form id="form1" runat="server">
        <asp:ScriptManager runat="server" ID="manager"
               OnAsyncPostBackError="HandleError">
        </asp:ScriptManager>
        <asp:UpdatePanel runat="server" ID="panel">
            <ContentTemplate>
               <asp:Button runat="server" ID="bt" Text="gerar erro no servidor"
                OnClick="handleClick" />
            </ContentTemplate>
         </asp:UpdatePanel>
   </form>
</body>
</html>

As you can see, when the user clicks the button, he'll get a divide by zero exception error on the server side. The previous page shows how you could log the error and return a friendly error message back to the client (the AsyncPostBackErrorMessage was introduced in this version and lets us define the error message which is returned to the client when an exception occurs on the server side). If you run the page, you'll notice that you'll still get the alert message, but this time, it'll show our fridendly error message.

If you want, you can drop the standard alert message and show the error in any way you see fit. To illustrate the steps necessary to perform this operation, I'll start by adding a DIV ccontrol that will be used as a place holder for showing the error returned from the server:

<div id="err"></div>

The next thing we need to do is to handle the endRequest event which is fired by the PageRequestManager object which is present in all the pages that use UpdatePanels:

<script type="text/javascript">
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest( endRequest );
   function endRequest( sender, e ) {
        if( e.get_error() ){
               document.getElementById("err").innerText =  e.get_error().description;
               e.set_errorHandled( true );
        }
   }
</script>

I start by adding a method that will handle the endRequest event by using the add_endRequest method over the Sys.WebForms.PageRequestManager global object. The method starts by checking if there's an error (by using the get_error method) and, when it finds one, it gets its description (through the description field) and sets the errorHandled field of the EventArgs object used to true so that the default alert message isn't shown to the user. Though the previous code is really simple, there's nothing preventing you from using the toolkit behaviors to get similar results to the ones that we had in the previous CTPS (btw, you can also stop processing the server side error event if you don't need logging and do everything in the client side: you're the one that need to decide on what's best here!).

For those that want to show a default error page, then there's still one additional property exposed by ScriptManager which you'll like: AllowCustomerErrors. When you set this property to true, you're saying that ScriptManager should check for a custom error page associated with the current error an show it to the user. To illustrate its usage, lets start by adding the following to the web.config file:

<customErrors mode="On">
     <error statusCode="404" redirect ="error.aspx"/>
</customErrors>

And now lets run the following page:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void HandleClick(object sender, EventArgs e)
{
     this.Server.Transfer("nopage.aspx"); //don't do this in reall AJAX pages!!!!!
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
      <title>Untitled Page</title>
   </head>
<body>
<form id="form1" runat="server">
   <asp:ScriptManager runat="server" ID="manager"
        AllowCustomErrors="true" />
   <asp:UpdatePanel runat="server" ID="panel">
       <ContentTemplate>
          <asp:Button runat="server" id="bt" Text="postback"
               onclick="HandleClick" />
      </ContentTemplate>
    </asp:UpdatePanel>
</form>
</body>
</html>

First, you should note that you should never use a Server.Transfer instruction on an ajax page. I'm using it since it's simplest way I could think of getting a known 404 error. Now, back to the important things: the AllowCustoErrors property. Since i've set it to true, when ScriptManager handles an exception during an async postback, it'll read the config file and see if there's any error page associated with the current error. If there is, it'll just send an AJAX message to client which instructs the browser to redirect the user to the desired page.

As you have seen, there's now a lot more control over the way exceptions are handled during a partial postback request. You do have to write more code than in the previous versions, but it's also true that the current release is a lot more flexible than the previous one.

Filed under: ,

Comments

# Mike McIntyre said on Monday, October 30, 2006 8:59 AM

I get an exception when I use the samle code.

At the point where the program tries to divide by 0 I get the a pop-up in the IDE that says:

"DivideByZeroException" was not handled by user code."

To try the code I created a new VS 2005 ASP.NET Ajax Beta 1 project and pasted your code into a web page.

I have been having the same issues when I try to use the new error handling based on the "How to: Customize Error Handling in Partial-Page Updates" tutorial at:

http://ajax.asp.net/docs/tutorials/usingMsAjaxLibrary/displayErrorMessage.aspx

And, when I run the example at that URL it doesn't appear to work either.  It returns a page that says the Ajax web site is down everytime and yet the site is not down.

Have you been able to get your code to work?

If so, do you have any thoughts on why it would not work for me?

Thanks,

Mike McIntyre

# Luis Abreu said on Monday, October 30, 2006 12:47 PM

Hi.

I'm assuming that you're hitting the start debugging option in the VS IDE (a full green arrow head). if that is the case, you'll always have the exception  popup in the IDE. hitting that button again should make you go throught the exception and you should get the expected results.

btw, if you right click the page and choose view in browser, you should get the normal behavior without the IDE popup.

# Mike Weerasinghe said on Monday, October 30, 2006 9:24 PM

Hi Luis,

Does the ScriptManager AsyncPostBackError fire HttpApplication Error event?

The reason I am asking is because I have a web site that uses ELMAH(Error Logging Modules And Handlers) module from GotDotNet to log all ASP.NET errors to a database. It works by hooking in to HttpApplication Error event. Previous CTP versions of Ajax (Atlas) did not log any errors to the database when and Ajax related error occured.

Do you have any information on this?

Thanks for a great article.

Mike

# scottgu said on Friday, November 03, 2006 3:41 AM

Luis Abreu是ASP.NET MVP,在 http://msmvps.com 博客站上拥有一个精彩的博客。今天早些时候,他贴了一篇精彩的教程帖子,描述如何使用ASP.NET AJAX Beta1版中的一些新特性,来给你的应用添加更健壮(robust)的出错处理。我强烈推荐你去阅读以及为将来之用而收藏它。

# Atteint de Javascriptite aigüe said on Tuesday, November 28, 2006 2:27 AM

Avec les anciennes versions d'Atlas la gestion des erreurs avec les UpdatePanels n'étaient pas des plus

# SeBeuH's WebBlog said on Saturday, December 02, 2006 11:50 AM

Je me suis retrouv lors d'un dev d'une application Web dans une petite galre avec l'ASP.NET AJAX Extention ! La situation est simple, j'ai une page ASPX contenant une gridview dans un UpdatePanel qui est protge par un formulaire...

# Amit Lohogaonkar said on Wednesday, December 27, 2006 1:33 AM

We have aspx pages with ajax beta and updatepanels.

When session ends it shows

Sys.WebForms.PageRequestManager message received from server could not be parsed

I tried scriptmanager endrequest but it still shows the same error

How to handle this error when session ends.

amit.lohogaonkar@comdaq.net

# Rob Kent said on Thursday, January 11, 2007 8:11 AM

Thanks for the useful tip and code. However, I would like to add one caveat to people who are using the scriptmanager on a Master page, as I am.

If you wire up the client-side endrequest handler, either in a global script file or in a master page script block, it will error if the content page does not contain an update panel (possibly other Ajax controls will do).

It seems that the script include for the WebForms lib is only generated in this instance, which means that when the event handler is assigned you get the error: 'Sys.WebForms.PageRequestManager is null or not an object'. If you step into the debugger at this point and look at the Script Explorer, you will see that there is only one ScriptResource.axd file showing.

If you make the assignation conditional, it will avoid the error: if (Sys.WebForms != null) Sys.WebForms.PageRequestManager.getInstance().add_endRequest( endRequest );

# Lucian N. said on Friday, January 26, 2007 2:29 PM

Luis,

Please comment a bit this scenario: I want AllowCustomErrors="false" in ScriptManage and <customErrors mode="Off"/> in web.config because I lilke to custom handle the errors in global.asax (or in a http module class) based on a custom exception class I built on top of ApplicationException.

Made a few tests on current MS AJAX RTM and it looks like there is no way to make ScriptManager to skip its verifications. Is there something I should know, or this scenario is just not possible yet?

Thanks in advance,

Lucian

# アフェリエイトのためのブログ製作までの流れ said on Monday, February 05, 2007 7:28 AM

TB失礼します。ブログ記事とても参考になりました。ID Manager で検索していてこちらにたどり着きました。またお邪魔させて頂きますね。今後とも宜しくお願いします。

# Gopala said on Thursday, February 22, 2007 4:03 AM

Hi,

I am facing the same problem as Amit stated above....

When Session ends and i try to do a partial postback i get the same error popup.

# Jerome's TOT said on Thursday, March 01, 2007 12:15 PM

ASP.NET AJAX: How to call client-side Javascript once an UpdatePanel request is over

# aarst said on Saturday, May 12, 2007 3:46 PM

higuys!What yourblog powered by?

# yinix said on Tuesday, June 05, 2007 12:07 AM

【原文地址】Tip/Trick:HandlingErrorswiththeUpdatePanelcontrolusingASP.NETAJAX【原文发表日期】Sunday,Oc...

# majid said on Thursday, June 07, 2007 7:40 AM

i am using detailview in update panel, infact inside nested update panel

but it is not working

If any one can help me to sort it out

do mail me at

ismail.majid@gmail.com

If you know any link that can help me

Regard majid

# Sebastien.warin.fr» Blog Archive » FormAuthentication, Session et UpdatePanel : PageRequestManagerParserErrorException said on Tuesday, June 12, 2007 5:14 AM

Pingback from  Sebastien.warin.fr&raquo; Blog Archive &raquo; FormAuthentication, Session et UpdatePanel : PageRequestManagerParserErrorException

# Michael's Coding Den said on Wednesday, June 13, 2007 2:01 PM

.NET Tips &amp; Tricks Michael Nemtsev, Microsoft MVP Last update: June 13 , 2007 Document version 0

# AAS said on Saturday, June 16, 2007 11:55 AM

HM2irD Hey, there is what you need.

# ASP.NET AJAX Forum Posts said on Thursday, June 21, 2007 12:23 AM

I have a page that has a scriptmanager, updatepanel, and timer in it. This page is iframed by another

# Papayma said on Friday, June 29, 2007 9:41 PM

Thank you.

# Papayma said on Friday, June 29, 2007 9:41 PM

Thank you.

# Papayqv said on Saturday, June 30, 2007 7:48 PM

Thank you!

# Papaywq said on Sunday, July 01, 2007 2:12 AM

Thank you!

# AAS said on Sunday, July 01, 2007 7:08 PM

Hey, there is what you need.

# AAS said on Sunday, July 01, 2007 7:23 PM

Hey, there is what you need.

# André Luiz Sobreiro said on Monday, July 16, 2007 1:49 PM

Thank you. It's really a very good article.

I'd like to extend this with using of master page.

In my case, the script manager is on the master page, and I'd like to have a handler for each page. Its a big project, end in my reality I am developing webparts for a sharepoint project where the script manager is not under my hands. My solution was to make a pattern with the sharepoint team to have the ID of the script manager control, so, I can find the control with the findcontrol method in my webpart and add my especific handler to the "AsyncPostBackError" event. I dont like this kind of thing. I couldnt even use the scriptmanager proxy to do this. So, does anyone have a better solution ? thanks in advance. André Luiz Sobreiro

# Alex said on Saturday, July 21, 2007 11:33 AM

Hi2all! Can me anyone give a little help?

How could I debug atlas to find out where the exception is thrown?

I've got a gridview in updatepanel and there is a linkbutton, when I click it, atlas alerts with exception message, but I can't determine why..

The exception is thrown only in IE6

# Robert said on Thursday, July 26, 2007 11:35 PM

Managed Hosting, Colocation and Data Center Services by victoryushchenkonashpresudent ...

# Hillary said on Tuesday, August 21, 2007 9:01 AM

Hello, nice site look this:

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

+1 Interesting theme I can place it with myself on blog?

End ^) See you

# Hillary said on Wednesday, August 22, 2007 5:32 AM

Hello, nice site look this:

End ^) See you

# car detail said on Thursday, September 13, 2007 10:43 PM

Hi! It`s no bad.

See my site too!<br>

<a href=" car-detail.infocatalogs.info/car-detail-undefined-used.html ">car detail undefined used</a><br>

Bay, bay.

# ford 9n tractor said on Saturday, September 15, 2007 12:04 AM

Hi! It`s no bad.

See my site too!<br>

<a href=" ford-tractor.infocatalogs.info/ford-9n-tractor.html ">ford 9n tractor</a><br>

Bay.

# JR said on Monday, October 15, 2007 8:25 PM

Thank you.  GREAT STUFF

# Jacky_xu said on Tuesday, October 23, 2007 8:37 PM

[1]PHPonIIS7w/FastCGI(IIS7中的PHP和FastCGI模块)

最新版本的IIS7.0即将随着WindowsVista一同发布,在极大增强了其主要支持的ASP.NET...

# tron said on Thursday, January 10, 2008 12:14 PM

<a href= http://index1.sdsob.com >curtis w lassiter</a>

# tron said on Thursday, January 10, 2008 11:19 PM

<a href= http://index1.sdsay.com >breast nodularity at a posterior depth</a>

# goro said on Monday, January 14, 2008 11:49 AM

<a href= http://index1.gofjf.com >frederick douglass biography</a>

# Matt said on Monday, July 21, 2008 6:43 AM

This is good - I don't agree with the custom error page handling though. I see this a lot in examples and developers do not realize the effect this has on spiders:

<error statusCode="404" redirect ="error.aspx"/>

If a spider gets this, it will punish or more likely remove the page from the search engine index. The default redirect for asp.net custom error pages should be statuscode 500, when spiders see this code they assume an error has occured and will come back later - as opposed to assuming the page is not there anymore. You should have a custom 404 page too, but this should be used automatically by .net when a page is not found or has moved - not for handling errors.

I know this is not an seo asp.net article, but part of good error handling should take into account all kinds of visitors - spiders and humans. If a really important page gets dropped from Googles index due to a simple error, that won't be nice.

# Hani - HaniKhanafer@yahoo.com said on Monday, June 29, 2009 1:46 PM

Dear Writer,

Kindly note that i am facing a problem that i am not getting the alert message from AJAX which made the system show the regulat asp.net error.

Kindly note that i need just to let AJAX shows the alert message without any modifications to it.

i am using ASP.net 3.5 and the latest version of AJAX.

please send me replies to hanikhanafer@yahoo.com

Hani

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover