2

In my ASP.NET Core app I was registering an IExceptionFilter to globally catch exceptions and replace the Result returned to the client. I'm now switching to the minimal API way of doing things, but I'm not finding where I register that filter.

In the ASP.NET Core version I'd register that filter in the AddController method.

I then tried doing this:

builder.Services.AddProblemDetails();

var app = builder.Build();

app.UseExceptionHandler(x => {
    x.Run(async context => {
        var exception = context.Features.Get<IExceptionHandlerFeature>()!.Error;

        var details = new ProblemDetails {
            Status = StatusCodes.Status500InternalServerError,
            Title = "An unexpected error occurred",
            Detail = exception.Message
        };

        switch (exception) {
            case DisplayToUserException:
                details.Status = StatusCodes.Status400BadRequest;
                context.Response.Headers.Add("X-Display-To-User", exception.Message);
                break;
            case ...
        }

        await Results.Problem(details).ExecuteAsync(context);
    });
});

That doesn't seem to change the response though.

Also, according to the docs, that only works in production mode. I need it to work in debug mode as well though because I'm using this to simplify return values. If something deep in a repository throws an exception, I want the response to be modified.

Gargoyle
  • 9,590
  • 16
  • 80
  • 145

1 Answers1

1

While Minimal APIs support adding filters to endpoints usual approach for handling exceptions in modern ASP.NET Core including Minimal APIs is by using corresponding middlewares. For example:

// register it closer to the start of the handling pipeline
app.UseExceptionHandler(exceptionHandlerApp 
    => exceptionHandlerApp.Run(async context 
        => await Results.Problem()
                     .ExecuteAsync(context)));

app.Map("/exception", () 
    => { throw new InvalidOperationException("Sample Exception"); });

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132