aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

WebHost needs an error flag

Open davidikin45 opened this issue 8 years ago • 8 comments

When the setting CaptureStartupErrors is set to True and you do Db initialization after building the WebHost there is no way to tell if an exception has occured during configuration. In my case I am getting a service from WebHost.Services which throws an exception because it doesn't exist. The end result is not seeing the configuration exception

davidikin45 avatar Sep 29 '18 06:09 davidikin45

@divega @ajcvickers This is a result of doing more things in Program.Main instead of Startup. That change that we made to the pattern in 2.1 means that you don't catch these errors anymore. Do you guys have any thoughts on this?

davidfowl avatar Sep 29 '18 06:09 davidfowl

                public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .UseSetting("detailedErrors", "true")
                .CaptureStartupErrors(true)
                .UseKestrel(options =>
                {
                    options.AddServerHeader = false;
                }
                )
                .UseAutofac()
                .UseConfiguration(Configuration)
                .UseSerilog()
                .UseStartup<TStartup>();
                
                var host = CreateWebHostBuilder(args).Build();

                //Db initialization
                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;
                     //Throws Exception
                    var taskRunner = services.GetRequiredService<TaskRunner>();
                   
                }

                host.Run();

davidikin45 avatar Sep 29 '18 06:09 davidikin45

For the time being will use services.GetService instead and check for null but would be nice to have a flag

davidikin45 avatar Sep 29 '18 07:09 davidikin45

@davidfowl he's not asking about catching the EF error but being able to see the underlying Startup error, or at least see that there was one captured.

Tratcher avatar Sep 29 '18 14:09 Tratcher

I see, I misunderstood. We could store the exception and expose it on a service I guess. Is that what you're asking for? Why are you using CaptureStartupErrors in the first place? Why not let it throw and catch yourself.

davidfowl avatar Sep 29 '18 15:09 davidfowl

@davidfowl I do that for unhandled exceptions while the host is running but I like the idea of displaying the error page for startup configuration exceptions

davidikin45 avatar Sep 29 '18 15:09 davidikin45

So you just want access to the exception so you can log it again? (The web host already logs it). Or do you just want to use it so you can avoid the EF code ?

davidfowl avatar Sep 29 '18 16:09 davidfowl

Use it to avoid EF Code

davidikin45 avatar Sep 29 '18 16:09 davidikin45