Always log startup exceptions

This commit is contained in:
Christian Weiss 2017-08-08 09:06:51 +02:00 committed by Justin Kotalik
parent a49db63f06
commit 07f96a444e
2 changed files with 47 additions and 3 deletions

View File

@ -191,7 +191,7 @@ namespace Microsoft.AspNetCore.Hosting.Internal
return builder.Build();
}
catch (Exception ex) when (_options.CaptureStartupErrors)
catch (Exception ex)
{
// EnsureApplicationServices may have failed due to a missing or throwing Startup class.
if (_applicationServices == null)
@ -199,13 +199,18 @@ namespace Microsoft.AspNetCore.Hosting.Internal
_applicationServices = _applicationServiceCollection.BuildServiceProvider();
}
EnsureServer();
// Write errors to standard out so they can be retrieved when not in development mode.
Console.Out.WriteLine("Application startup exception: " + ex.ToString());
var logger = _applicationServices.GetRequiredService<ILogger<WebHost>>();
logger.ApplicationError(ex);
if (!_options.CaptureStartupErrors)
{
throw;
}
EnsureServer();
// Generate an HTML error page.
var hostingEnv = _applicationServices.GetRequiredService<IHostingEnvironment>();
var showDetailedErrors = hostingEnv.IsDevelopment() || _options.DetailedErrors;

View File

@ -851,6 +851,45 @@ namespace Microsoft.AspNetCore.Hosting
}
}
[Fact]
public void StartupErrorsAreLoggedIfCaptureStartupErrorsIsTrue()
{
var builder = CreateWebHostBuilder()
.CaptureStartupErrors(true)
.Configure(app =>
{
throw new InvalidOperationException("Startup exception");
})
.UseServer(new TestServer());
using (var host = (WebHost)builder.Build())
{
var sink = host.Services.GetRequiredService<ITestSink>();
Assert.True(sink.Writes.Any(w => w.Exception?.Message == "Startup exception"));
}
}
[Fact]
public void StartupErrorsAreLoggedIfCaptureStartupErrorsIsFalse()
{
ITestSink testSink = null;
var builder = CreateWebHostBuilder()
.CaptureStartupErrors(false)
.Configure(app =>
{
testSink = app.ApplicationServices.GetRequiredService<ITestSink>();
throw new InvalidOperationException("Startup exception");
})
.UseServer(new TestServer());
Assert.Throws<InvalidOperationException>(() => builder.Build());
Assert.NotNull(testSink);
Assert.True(testSink.Writes.Any(w => w.Exception?.Message == "Startup exception"));
}
[Fact]
public void HostingStartupTypeCtorThrowsIfNull()
{