Getting Application's Last Encountered Unhandled Exception

While answering posts in forums.asp.net, I bumped into two questions asking how to get the last unhandled exception encountered by the web application and the challenge of preserving the stack trace and application state. The current version of asp.net just allows us to auotmatically redirect the user to the error page as specified thru web.config sections.

That can solve by using custom a HttpModule. The System.Web.HtttpApplication have this GetLastError() method. Below is a sample code, hope this helps.

[Language("C#")]
[TargetFramework("2.0" | "1.1")]

using System;
using System.Web;
namespace MyCompany.Project.HttpModules {
    public class ExceptionHandlerHttpModule: IHttpModule {

        public void Init(System.Web.HttpApplication Application) {
            Application.Error += new EventHandler(OnError);
        }

        protected virtual void OnError(object sender, EventArgs args) {
            HttpApplication app = ((HttpApplication)(sender));
            //you may pass the exception to your custom exception handler for logging and wrapping
            //or you may alter the response stream to display a friendlier error message
            Session["LastError"] = app.Server.GetLastError();
        }
    }
}

[web.config]
        <httpModules>
            <add name="ExceptionHandlerHttpModule" type="MyCompany.Project.HttpModules.ExceptionHandlerHttpModule"/>          
        </httpModules>

To share you my case, I just downloaded and modify this cool project from www.codeproject.com and customize to suit our needs. As I mentioned before, it is extremely important for me to preserve the last application's state when the exception was encountered. I am pertaining to cookies, server variables, session and application objects, client's browser settings and platform, assemblies loaded, stack trace and remote host and referers.

This is just an HttpModule that I plugged into http request pipeline and handles all applications unhandled exceptions gracefully. I compiled this module and made available to our applications, this way we get rid of that "yellow page of death". ;)

http://www.codeproject.com/aspnet/ASPNETExceptionHandling.asp