In the interest of always showing a "friendly" error page to users when they visit a site I have a catch-all at the in the Global.asax page, the majority of errors are handled by filters which seems to be the preferred method. For the most part, this works fine. However, during Application_Start, the Application_Error event (understandably) does not get triggered.
My Application_Start event contains some initialisation code which is dependent on a service call, so an easily defined point of failure is if the service is unavailable for whatever reason. The only way I've found to get around 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 the Application_BeginRequest
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (StartUpException != null)
{
HandleErrorAndRedirect(StartUpException);
HttpRuntime.UnloadAppDomain();
Response.End();
}
}
This works, but seems like a bit of a hack. I'm also not sure about the consequences of calling UnloadAppDomain, or what would happen if multiple requests arrived. Is there a better way to manage this?