Handling unhandled exceptions from AJAX.Net postback

A couple of days ago, I had to deal with a bug in a page I wrote. The page contains a couple of UpdatePanel controls. For some reason, when an exception was thrown during the PostBack of one of this panels, the page was not redirected to our error page (which is the case for all none AJAX postbacks), but it's message is displayed in an alert popup. It's a security hole that can expose internal information (The bug was detected when my team leader, Doron, who got a message which contains a SQL statement which failed to run).
Further more, if an exception is not redirected to the error page it was not handled. Our error page contains the logging of the unhandled exceptions.

So I started to dig in.

I found out that unhandled exceptions in ASP.Net Ajax are handled by an event in the ScriptManager: AsyncPostBackError.
You can register to this event, handle the exception (log ,etc...), and override the error message which will be displayed (If this wasn't done already done by your exception handling framework) by setting the property AsyncPostBackErrorMessage to the message that you want to display.

In our case, because we are using a Master page for the pages in our site, I registered to the event in the Master page, handled it with Enterprise Library, and replaced the message (in case the Enterprise Library configuration haven't done so already):

protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)  
    ScriptManager1.AsyncPostBackErrorMessage = "exception handled";

This way, I didn't had to replicate the handling code in all of our AJAX pages.

Use it wisely.

Yossi Shmueli

Keeping it green since 1995

comments powered by Disqus