Is there a way to display a custom error page when an exception occurs during the startup phase of an ASP.NET Core application? For example, if an exception occurs (db is down etc.) in any of the methods of the Startup class i.e. Configure, ConfigureServices, Startup.Ctor etc.?
I think that using the following code isn't going to help me
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
as the middleware pipline isn't constructed yet. So the line
app.UseExceptionHandler("/Home/Error");
isn't executed as a consequence.
Is there a way to display a custom error page if an error occurs at this stage?
thanks
ashilon
In the Configure method you're configuring the HTTP pipeline to handle requests. Since there is no request when your application starts, the pipeline is never executed. In fact, as you mentioned the exception might occur when you're actually configuring the pipeline.
The hosting layer provides a way to capture startup errors and show a decent error page. You can use the CaptureStartupErrors(true) on the IWebHostBuilder interface. This is where you configure the hosting layer of your application and is typically located in Pogram.cs. For example:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.CaptureStartupErrors(captureStartupErrors: true) // Add this line
.Build();
host.Run();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With