Handling exceptions in Application_Start()

What do you do to handle a potential exception occurs during Application_Start() in your ASP.NET MVC 5 project?

ASP.NET shows the following page if you don’t do anything:

YSOD (Yellow Screen of Death)

This is not desired on a production site. Here is my research on this issue.

<customErrors> in web.config

Normally configuring <customErrors> in web.config would make ASP.NET show a predefined page for this error.

This unfortunately doesn’t work for this case. ASP.NET infrastructure depends on HttpApplication instance initialized correctly and it fails to honor <customErrors> if Application_Start() fails. It results in the following screen:

Handling Application_Error() event

My next option was Application_Error() event handler.

The event handler does fire, but Transfer() throws a HttpException complaining that Request is not available in the context yet.

This is because ASP.NET creates a special instance of HttpApplication that is not associated with any Request object at start-up. It only creates a new instance associated with a Request object once it successfully initializes the special instance by running Application_Start().

Final Solution

Since successful initialization of HttpApplication is crucial for ASP.NET functionality, I’ve decided to catch the exception occurred during Application_Start() and report the exception later during Application_BeginRequest().

With this approach, however, ASP.NET is not aware that it failed to initialize the application, and Application_Start() will not run again.

A solution is that you can call HttpRuntime.UnloadAppDomain() in Application_ResponseCompleted(). This will ensure ASP.NET create new appdomain for next request and run Application_Start() again.

Application_BeginRequest() is reporting the error back to ASP.NET by calling AddError(). You will still need to have <customErrors> in web.config to show a custom error page.