Exception Handling: Reloading the page that bit ya
An interesting question came through today regarding an article I did about custom error pages:
Is there a way to handle errors in a global sense and not have to re-direct to an error page? I'd like the exception information to be caught at either the page or application level and to keep the user on the same web page with an error message at the top of the page.
Sure, though it's a bit of work. Something to consider first: In theory the reason you want to redirect to an error page is that you have an important bit of control over it -- it won't throw further exceptions. If a page throws an exception then you want to be sure it is safe to reload that same page. If the page triggers the exception over and over and eventually times out with a browser error, users might not be better off. That said...
The ASP.NET custom error page (as configured with the customErrors element in web.config) is built into the Page object's OnError event. You could create your own Page class which inherits from the base Page and override OnError to redirect back to the page orginally requested. GetLastException will still be available for display.
At the Application_Error level you could also get the full URL requested and redirect back to it rather than to an error page. My sample code shows how to display the requested URL on the error page, it shouldn't be hard to move that string into the Application_Error event of the global.asax. As I recall, it doesn't include the original QueryString (if it exists), you may want to add that.
If redirecting the user back to the same page, you could add a parameter for Page_Load to pick up on so you can take some control to ensure the exception is not triggered again. If you choose to write a class which inherits from Page, it might be a thought to add your own Page_ErrorRecovery event (and yes, this is easier to recommend than to build).
On a different tack, a simple approach I've seen (though one that redirects to an error page) is in the source code for the ASP.NET Forums 2.0. Check out the ForumsHttpModule.cs code.
The exception management strategy in ASP.NET Forums 2.0 is:
a) Define a set of application-specific exception types.
b) Build a logging mechanism.
c) Trap the custom Application Exceptions in an HttpModule, log them and redirect the user to a page that indicates somehing went wrong.
The features are similar to what I put in the article though my goal was to preserve exception details for display back to the user. What I like about this source is its simplicity; it reads well and is easy to extend. Whichever route you take, it's a free download well worth a read. If you like its pattern, you can always change its redirects to go back to the page that bit ya.