Hi,
I'm currently developing a REST API with ASP.NET Core 8.0.3. There I want to use a custom exception handler that handles undhandled exceptions. As mentioned in the docs I created a GlobalExceptionHandler
class that implements IExceptionHandler
.
My Program.cs
looks like this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
...
builder.Services
.AddControllers(opt => { opt.Filters.Add<ActionFilter>(); })
.AddJsonOptions(opt => { opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); });
...
var app = builder.Build();
app.UseExceptionHandler();
...
This basically works as expected and my exception handler is being called, if an unhandled exception occurs. The first thing that I'm doing in my exception handler is to log the error. After creating a ProblemDetails
response my exception handler method returns true
, because the exception has been handled. There is only one problem:
When an exception occurs, it is being logged twice!
The first time it is being logged by ExceptionHandlerMiddlewareImpl.cs
in the method private async Task HandleException(HttpContext context, ExceptionDispatchInfo edi)
> DiagnosticsTelemetry.ReportUnhandledException(_logger, context, edi.SourceException);
. This always happens BEFORE my GlobalExceptionHandler
is being called.
An unhandled exception has occurred while executing the request
And only then my GlobalExceptionHandler
is being called, where I actually want to log and handle the exception.
So, what am I missing here? What am I doing wrong? Shouldn't my GlobalExceptionHandler
be the first that is being called when an unhandled exception occurs? How to prevent ExceptionHandlerMiddlewareImpl.cs
from logging the exception before my handler?
Many thanks in advance