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?
For built-in UseDeveloperExceptionPage
, it did not expose any extension method to custom 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;
}
});
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