LA.NET [EN]

Oct 29

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. S
ince 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.

36 comments so far

  1. Mike McIntyre
    1:59 pm - 10-30-2006

    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

  2. Luis Abreu
    5:47 pm - 10-30-2006

    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.

  3. Mike Weerasinghe
    2:24 am - 10-31-2006

    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

  4. Amit Lohogaonkar
    7:33 am - 12-27-2006

    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

  5. Rob Kent
    2:11 pm - 1-11-2007

    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 );

  6. Lucian N.
    8:29 pm - 1-26-2007

    Luis,

    Please comment a bit this scenario: I want AllowCustomErrors=”false” in ScriptManage and 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

  7. Gopala
    10:03 am - 2-22-2007

    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.

  8. aarst
    8:46 pm - 5-12-2007

    higuys!What yourblog powered by?

  9. majid
    12:40 pm - 6-7-2007

    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

  10. AAS
    4:55 pm - 6-16-2007

    HM2irD Hey, there is what you need.

  11. Papayma
    2:41 am - 6-30-2007

    Thank you.

  12. Papayma
    2:41 am - 6-30-2007

    Thank you.

  13. Papayqv
    12:48 am - 7-1-2007

    Thank you!

  14. Papaywq
    7:12 am - 7-1-2007

    Thank you!

  15. AAS
    12:08 am - 7-2-2007

    Hey, there is what you need.

  16. AAS
    12:23 am - 7-2-2007

    Hey, there is what you need.

  17. André Luiz Sobreiro
    6:49 pm - 7-16-2007

    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

  18. Alex
    4:33 pm - 7-21-2007

    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

  19. Robert
    4:35 am - 7-27-2007

    Managed Hosting, Colocation and Data Center Services by victoryushchenkonashpresudent …

  20. Hillary
    2:01 pm - 8-21-2007

    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

  21. Hillary
    10:32 am - 8-22-2007

    Hello, nice site look this:

    End ^) See you

  22. car detail
    3:43 am - 9-14-2007

    Hi! Its no bad.
    See my site too!
    car detail undefined used
    Bay, bay.

  23. ford 9n tractor
    5:04 am - 9-15-2007

    Hi! Its no bad.
    See my site too!
    ford 9n tractor
    Bay.

  24. JR
    1:25 am - 10-16-2007

    Thank you. GREAT STUFF

  25. tron
    6:14 pm - 1-10-2008
  26. tron
    5:19 am - 1-11-2008
  27. goro
    5:49 pm - 1-14-2008
  28. Matt
    11:43 am - 7-21-2008

    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:

    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.

  29. Hani - HaniKhanafer@yahoo.com
    6:46 pm - 6-29-2009

    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

  30. Buy Ambien
    2:16 pm - 2-13-2010

    bads tempted sized overnight webster absorptive clots landowner borrowing chantilly kkeksa
    ambisoltersos makalavertonicos

  31. Janitorial Supplies
    3:59 pm - 3-19-2010

    We actually use something similar to this on our site, however it doesn”t catch 50X errors – do you know a way around this? Would be great to catch all errors without having to hit the event viewer.

    Thanks

    Loren

  32. mathewmmathew-nest
    9:20 am - 8-4-2010

    Problem :

    Sys.WebForms.PageRequestManagerParserErrorException will occur when redirecting ur page ,lets say button click inside UpdatePanel in aspxAjax

    Soln :

    1. Add a “GoTo” button in ur aspx page where update panel is using and add it outside Update panel

    1a. In ur code assign ur just registered userID to session variable , say Session[“UseridJustregistered”]= Id from DB or UsernameField

    2. respose.redirect(“regSucces.aspx?urlid=””+Session[“UseridJustregistered”]+”””);

    3. Check if Session[“UseridJustregistered”] is null or not

    –> This is OLD Classic ASP way which can solve our problem , by the time microsoft find a solution we can tackle it this way <–

  33. RichardsonCharlene26
    12:02 am - 11-28-2010

    If you”re in uncomfortable position and have no money to go out from that, you would have to take the loan. Just because it would help you emphatically. I take secured loan every year and feel myself OK because of this.

  34. Data Center Services
    7:59 pm - 12-15-2010

    It”s amazing how bad people are with error handling, even Google gives some terrible messages.

  35. Abdul Wakeel
    10:18 am - 1-5-2011

    Can i handle the scriptManager Error in Global.ascx or web.config and Log them to database.

    Although i found the solution in master page where scriptManager is Used. But i want this in global.ascx

  36. luisabreu
    11:23 am - 1-5-2011