Capturing ASP.NET Application Startup Exceptions
It has become common practice to perform tasks during an ASP.NET applications start up process. These tasks may include registering routes, configuring filters, wiring up third party dependencies, and so much more. Here is the default ASP.NET MVC application startup code pulled from the sample.
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
These tasks are crucial to the function of the application, but they don't always execute cleanly. Exceptions in the startup process can mean the application never got a change to wire up exception handlers. This can make it difficult to debug issues in production, causing us to turn customErrors
off.
<customErrors mode="Off" />
To insure you capture application startup exceptions, remember to implement Application_Error
.
private void Application_Error(object sender, EventArgs e) { // a static boolean at the application level if (FailedToStartUp) { // Step 1 : write to a dependable logging storage // option 1 : Trace // option 2 : Raygun // option 3 : Filesystem // Step 2 : Redirect to non-app based Error page // obviously needs to exist outside your app // since it failed to startup } }
Now we should get a log message that lets us know what the exception is, and additionally our users get to see an error page that isn't of the red and yellow variety. Note, it may be the default error logging mechanism that we've chosen that is causing our application failure. I recommend having a fallback logging mechanism if possible; Trace
is a safe bet.
Khalid Abuhakmeh – Software Developer and All Around Nice Guy
原文链接:http://www.khalidabuhakmeh.com/capturing-asp-net-application-startup-exceptions