UpdatePanel Exception Handling

Chris picture Chris · Dec 1, 2009 · Viewed 14.1k times · Source

Where exceptions occur in the UpdatePanels I've implemented in the ASP.NET web app I'm building, they cause a JavaScript error on the page with some high level error output available in the alert. This is OKish for development, but as soon as the system is in Production, it's obviously no good for multiple reasons. I can surround troublesome activities with Try Catch etc to control the Javascript error but in some cases, I want to take actions on the main page etc to support the user experience.

How do I go about handling errors that occur in UpdatePanels gracefully to provide a seamless and Javascript error free implementation?

Answer

Rob Windsor picture Rob Windsor · Dec 1, 2009

You can use a combination of the AsyncPostBackError event on the ScriptManager (server-side) and the EndRequest event on the PageRequestManager (client-side) to fully handle server-side errors when using the UpdatePanel.

Here are a couple resources that should help you:

Customizing Error Handling for ASP.NET UpdatePanel Controls

Error Handling Customization for ASP.NET UpdatePanel

Here's a simple example:

// Server-side
protected void ScriptManager1_AsyncPostBackError(object sender, 
    AsyncPostBackErrorEventArgs e)  {
    ScriptManager1.AsyncPostBackErrorMessage =
        "An error occurred during the request: " +
        e.Exception.Message; 
}


// Client-side
<script type="text/javascript">
  function pageLoad()  {
    Sys.WebForms.PageRequestManager.getInstance().
        add_endRequest(onEndRequest);  
  }

  function onEndRequest(sender, args)  {
    var lbl = document.getElementById("Label1");
    lbl.innerHTML = args.get_error().message;
    args.set_errorHandled(true);
  }
</script>