I have the following code in my ASP.NET Core application to handle errors:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(builder =>
{
builder.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var loggingService = context.RequestServices.GetService<ILoggingService>();
var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();
if (exceptionFeature != null)
{
Exception ex = exceptionFeature.Error;
Console.Error.WriteLine(ex.Message + " " + ex.StackTrace);
loggingService.Error(ex);
}
});
});
}
However, when being in a Development environment, I would like to use both the UseDeveloperExceptionPage()
and the custom error handling for DB logging. But it seems that this does not work (the UseExceptionHandler()
disables the functionality of UseDeveloperExceptionPage()
).
Is there any way to achieve this, without writing the UseDeveloperExceptionPage()
code form scratch?
The built-in UseDeveloperExceptionPage
does not expose any extension method to customize the error process. You could try implement your own middleware to log the error like:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
};
app.Use(async (context, next) =>
{
try
{
await next.Invoke();
}
catch (Exception ex)
{
//var loggingService = context.RequestServices.GetService<ILoggingService>();
//loggingService.Error(ex);
Console.Error.WriteLine(ex.Message + " My " + ex.StackTrace);
throw;
}
});