Why does ASP.NET Core log an unhandled exception when using a global exception handler?

Al Onestone 25 Reputation points
2024-03-15T11:37:51.4966667+00:00

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

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} vote

Accepted answer
  1. Anonymous
    2024-03-15T13:36:41.5666667+00:00

    Hi,

    There's no way to prevent "ExceptionHandlerMiddleware" running before your customhandler. But you could disable the default "ExceptionHandlerMiddleware" logs by following configuration in appsettings.json.

        "Logging": {
            "LogLevel": {
                "Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware": "None"
            }
    

    Then you could have only your customexceptionhandler logs in the console

    User's image

    ******************************************************************************* 

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".  Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.