-
Notifications
You must be signed in to change notification settings - Fork 79
Description
Description
The ASP.NET Core exception handler middleware, UseExceptionHandler()
, is responsible for catching and processing unhandled exceptions from ASP.NET Core requests.
In .NET 8, we introduced IExceptionHandler
. Implementations of IExceptionHandler
are registered with dependency injection and invoked by the middleware. An implementation can return true
from IExceptionHandler.TryHandleAsync
to indicate that the exception has been handled. The middleware stops processing the exception once it has been handled.
In .NET 10, we're changing the default behavior so that the middleware no longer records diagnostics for exceptions handled by IExceptionHandler
.
Version
.NET 10 Preview 7
Previous behavior
The exception handler middleware recorded diagnostics about exceptions handled by IExceptionHandler
.
The exception diagnostics are:
- Logging
UnhandledException
toILogger
. - Writing the
Microsoft.AspNetCore.Diagnostics.HandledException
event toEventSource
. - Adding the
error.type
tag to thehttp.server.request.duration
metric.
New behavior
If IExceptionHandler.TryHandleAsync
returns true
, then exception diagnostics are no longer recorded by default.
Type of breaking change
- Binary incompatible: Existing binaries may encounter a breaking change in behavior, such as failure to load or execute, and if so, require recompilation.
- Source incompatible: When recompiled using the new SDK or component or to target the new runtime, existing source code may require source changes to compile successfully.
- Behavioral change: Existing binaries may behave differently at run time.
Reason for change
ASP.NET Core users have given feedback that the previous behavior was undesirable. Their IExceptionHandler
implementation reported that the exception was handled, but the error handling middleware still recorded the error in the app's telemetry.
We are changing ASP.NET Core to follow the behavior expected by users by suppressing diagnostics when IExceptionHandler
handles the exception. We're also adding configuration options to customize exception diagnostics behavior if needed.
Recommended action
If you want handled exceptions to continue recording telemetry, you can use the new ExceptionHandlerOptions.SuppressDiagnosticsCallback
option:
app.UseExceptionHandler(new ExceptionHandlerOptions
{
SuppressDiagnosticsCallback = context => false;
});
The context passed to the callback includes information about the exception, the request, and whether the exception was handled. Returning false
from the callback indicates that diagnostics shouldn't be suppressed. This restores the previous behavior.
References
- Issue: Unhandled exceptions are being logged before custom IExceptionHandler is being called dotnet/aspnetcore#54554
- PR: Add option to exception handler middleware to suppress logging dotnet/aspnetcore#59074
Affected APIs
UseExceptionHandler()
IExceptionHandler