In my previous post I wrote about adding an exception handler in global.asax and adjusting web.config to display user-friendly error messages in ASP.Net applications.
While the strategy works fine, exceptions raised during an AJAX request are not handled by that solution. As I found out, you still get a Server Error page, for example if the SortExpression in a GridView within an UpdatePanel references an invalid column name.
To catch Ajax-generated exceptions, you need to add a AsyncPostBackError to the ToolkitScriptManager of your page or masterpage:
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { Exception ex = e.Exception; Session["Application_Error"] = ex; Session["Application_Request"] = Request; Response.Redirect("error.aspx"); }
This sample code uses the same Session variables as in the previous post, and explicitly redirects to the same error page.