aspnetcore: AddExceptionHandler/UseExceptionHandler Fails in a non-Obvious Way

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

With the new AddExceptionHandler and IExceptionHandler APIs, engaging the exception handler with UseExceptionHandler is confusing. For example, this code fails;

using ExHandler;
using Microsoft.AspNetCore.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();

var app = builder.Build();

app.UseExceptionHandler();       // Doesn't work

app.MapGet("/", () => {
  throw new Exception("Bad things happen to good developers");
});

app.Run();

public class GlobalExceptionHandler : IExceptionHandler
{
  public async ValueTask<bool> TryHandleAsync(HttpContext httpContext,
    Exception exception,
    CancellationToken cancellationToken)
  {
    httpContext.Response.ContentType = "text/plain";
    httpContext.Response.StatusCode = 501;
    await httpContext.Response.WriteAsync($"It don't work: {exception.Message}");
    return true;
  }
}

To make this work, you must pass in an empty lambda to the `UseExceptionHandler’:

app.UseExceptionHandler(o => { }); // Works

Expected Behavior

Expected the empty call to UseExceptionHandler to work. Could not find documentation that explained this. ,

Steps To Reproduce

Example is at: https://github.com/shawnwildermuth/ExceptionHandlerRepro

Exceptions (if any)

I get an arcane message:

System.InvalidOperationException
  HResult=0x80131509
  Message=An error occurred when configuring the exception handler middleware. Either the 'ExceptionHandlingPath' or the 'ExceptionHandler' property must be set in 'UseExceptionHandler()'. Alternatively, set one of the aforementioned properties in 'Startup.ConfigureServices' as follows: 'services.AddExceptionHandler(options => { ... });' or configure to generate a 'ProblemDetails' response in 'service.AddProblemDetails()'.
  Source=Microsoft.AspNetCore.Diagnostics
  StackTrace:
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddlewareImpl..ctor(RequestDelegate next, ILoggerFactory loggerFactory, IOptions`1 options, DiagnosticListener diagnosticListener, IEnumerable`1 exceptionHandlers, IMeterFactory meterFactory, IProblemDetailsService problemDetailsService)
   at Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.<>c__DisplayClass5_0.<SetExceptionHandlerMiddleware>b__0(RequestDelegate next)
   at Microsoft.AspNetCore.Builder.ApplicationBuilder.Build()
   at Microsoft.AspNetCore.Builder.ApplicationBuilder.Build()
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__40.MoveNext()
   at Microsoft.Extensions.Hosting.Internal.Host.<<StartAsync>b__15_1>d.MoveNext()
   at Microsoft.Extensions.Hosting.Internal.Host.<ForeachService>d__18`1.MoveNext()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__15.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at Program.<Main>$(String[] args) in C:\projects\codingshorts\net8exhandler\test\ExHandler\Program.cs:line 17

.NET Version

8.0.100-rc.2.23502.2

Anything else?

Note the failure is uncommented out, and the one that works is commented out. If this is expected behavior, we need it to be well documented since it is unobvious behavior.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 23
  • Comments: 21 (6 by maintainers)

Most upvoted comments

Any updates here?

Still waiting for the update 👀

The connected PR has been closed.

We still facing this issue in 8.0.3, so we have to use the proposed workaround app.UseExceptionHandler(o => {});

Could you please reopen this issue?

For what i understand I can agree with @ghhv saying that the problem is how we configure the webApp, and not in the method itself.

I was having the same problem, and I was thinking I’d solved it with: app.UseExceptionHandler(()=>{}); but, actually, we’d just bypassed the correct exception management.

The real problem seems that you need to register a “default” response in case your IExceptionHandler return false (Even if every exception is correctly managed inside the IExceptionHandler).

Actually adding ‘AddProblemDetails()’ before your exception handler seems doing the trick:

        builder.Services.AddProblemDetails();
        builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
[...]
        var app = builder.Build();
        app.UseExceptionHandler();

but i’m not sure is the correct behaviour. I leave here microsoft link with the method explanation:

[…] code configures the app to generate a problem details response for all HTTP client and server error responses that don’t have body content yet[…]

Is there a reason you don’t want to add service.AddProblemDetails() to your Program.cs file?

The error message recommends doing one of the 3 things to fix:

  1. Set either ExceptionHandlingPath or ExceptionHandler property in the UseExceptionHandler method. — This is what you did as a workaround
  2. Add/Set some options in services.AddExceptionHandler
  3. Call service.AddProblemDetails

The first 2 seem like cases that should be done if you need to handle some special case. The 3rd seems like the ideal solution if you just want to use everything out of the box. I’ve done this in multiple services now and everything works as expected.

Since the error message specifies doing 1 of the 3 things, I’m not sure there’s actually an issue here other than maybe for the error message to be worded better and possibly suggest calling service.AddProblemDetails first.

Perhaps I’m missing something regarding why we wouldn’t want to do any of the 3 suggestions the error makes?

I’m also not seeing this issue when using an exception handler in combination with problem details. The order they’re added to the service collection shouldn’t matter.

builder.Services.AddExceptionHandler<ExceptionHandler>();
builder.Services.AddProblemDetails(options =>
{
	options.CustomizeProblemDetails = context =>
	{
		...
	};
});

app.UseStatusCodePages();
app.UseExceptionHandler();

If (and only if) the IExceptionHandler returns false, the exception is available in the customize action as ProblemDetailsContext.Exception. This makes sense, since I think the exception handler returning true means the exception does not propagate.

But letting an exception propagate so it appears in ProblemDetailsContext.Exception (e.g., so you can use it to add information to the problem details) triggers another bug. ProblemDetailsContext.ProblemDetails is always initialized as a 500 regardless of the status code set by the exception handler, and there’s no way to leverage the existing defaults to re-initialize it (#47978).

@davidfowl The whole pipeline is broken. They need to stop worrying about backward compatibility and just fix it.

I re-read this issue. @captainsafia made an attempt and there were some breaking change considerations. I see > 20 updates on https://github.com/dotnet/aspnetcore/issues/51888#issuecomment-2059642998. Has anyone in this issue looked at the PR and considered what the behavior should be given the potential breaking change?

I’d love to see more of a technical discussion here rather than asking for updates. This issue is in the backlog, it’s not going to get prioritized in its current state. If anyone feels really strongly about this and has time to dig in, that could really help get it unstuck.

Hi, Any updates on this Fix ?

PR open against main.

This is a good candidate for servicing to 8.0 as well.