Tuesday, September 01, 2009

Useful code to properly record and redirect an unhandled exception from Global.asax Application_Error Handler

    void Application_Error(object sender, EventArgs e)

    {

        // Code that runs when an unhandled error occurs

        string httpCode = ((HttpException) Server.GetLastError()).GetHttpCode().ToString();

        if (HttpContext.Current.Session != null)

        {

            HttpContext.Current.Session["LastError"] = Server.GetLastError();

            Server.ClearError();

        }

        switch (httpCode)

        {

            case "404":

                Response.Redirect("/Error/Error404.aspx");

                break;

            default:

                Response.Redirect("/Error/Error.aspx");

                break;

        }

    }

Post a Comment