dotnet / dotnet/aspnetcore

AddExceptionHandler/UseExceptionHandler Fails in a non-Obvious Way

Open
#51,888 26 comments 29 reactions 0 assignees View on GitHub
area-middleware
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] 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;

```cs
using ExHandler;
using Microsoft.AspNetCore.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddExceptionHandler();

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 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':

```cs
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.b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Builder.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.GenericWebHostService.d__40.MoveNext()
at Microsoft.Extensions.Hosting.Internal.Host.<b__15_1>d.MoveNext()
at Microsoft.Extensions.Hosting.Internal.Host.d__18`1.MoveNext()
at Microsoft.Extensions.Hosting.Internal.Host.d__15.MoveNext()
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.d__4.MoveNext()
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.d__4.MoveNext()
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
at Program.$(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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.