How can I handle errors in the Global.asax Application_Start?

It’s in the interest of always showing users a “friendly” error page when they visit the site. I have everything on the Global.asax page; most errors are handled by filters, which are apparently the preferred method. For the most part, this works great. However, during Application_Start, the Application_Error event (understandably) does not fire.

The My Application_Start event contains an initialization code that depends on the call to the service, so it is easy to determine the point of failure if the service is unavailable for any reason. The only way I found this is to do the following.

    private static Exception StartUpException;
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        Initialise();       
    }

    private void Initialise()
    {
        StartUpException = null;
        try
        {
            Bootstrapper.Initialise();
        }
        catch (Exception ex)
        {
            StartUpException = ex;
        }
    }

Then I have the following code in Application_BeginRequest

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (StartUpException != null)
        {
            HandleErrorAndRedirect(StartUpException);
            HttpRuntime.UnloadAppDomain();
            Response.End();
        }
    }

, . UnloadAppDomain , . ?

+5
1

​​App_Start, HttpContext , ; :

public class MvcApplication : System.Web.HttpApplication {    
    protected void Application_BeginRequest() {
        var context = this.Context;
        FirstTimeInitializer.Init(context);
    }

    private static class FirstTimeInitializer {
        private static bool s_IsInitialized = false;
        private static Object s_SyncRoot = new Object();

        public static void Init(HttpContext context) {
            if (s_IsInitialized) {
                return;
            }

            lock (s_SyncRoot) {
                if (s_IsInitialized) {
                    return;
                }

                // bootstrap

                s_IsInitialized = true;
            }
        }
    }
}
+3

All Articles