skip to content

In ASP.NET Core, how do you write and register an IExceptionHandler, and what does returning true or false from TryHandleAsync do?

level: middleimportance: must knowfreq 68%

answer

  1. added in ASP.NET Core 8
  2. ValueTask<bool> TryHandleAsync
  3. AddExceptionHandler<T>() registers a singleton
  4. registration order, first true wins
  5. still needs app.UseExceptionHandler()

basics

~20 s

Implement IExceptionHandler.TryHandleAsync, register it with AddExceptionHandler<T>() and call UseExceptionHandler(). Handlers run in registration order; true means the response is written and stops the chain, false passes the exception to the next handler or the fallback.

solid answer

~40 s

`IExceptionHandler` (ASP.NET Core 8 and later) has one method, `ValueTask<bool> TryHandleAsync(HttpContext, Exception, CancellationToken)`. You register each implementation with `builder.Services.AddExceptionHandler<T>()`, which adds it as a **singleton**, and you still need `app.UseExceptionHandler()` because only that middleware calls the handlers. On an exception the middleware clears the response, sets 500, then calls the handlers in registration order. Returning `true` says "I wrote the response" and stops the chain; `false` passes to the next one. If none returns true, the middleware falls back to the error path or delegate if configured, otherwise to `IProblemDetailsService` from `AddProblemDetails()`. With none of those, the pipeline throws at startup. In ASP.NET Core 10 an exception a handler handled is no longer logged by the middleware.

code

csharp · 20 lines
csharp
public sealed class BookNotFoundExceptionHandler(IProblemDetailsService problemDetails)
    : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
    {
        if (exception is not BookNotFoundException notFound)
        {
            return false; // not mine: the next handler or the fallback runs
        }

        httpContext.Response.StatusCode = StatusCodes.Status404NotFound;
        return await problemDetails.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = httpContext,
            Exception = exception,
            ProblemDetails = { Title = "Book not found", Detail = $"No book has ISBN {notFound.Isbn}." }
        });
    }
}

go deeper

for a junior

Know the three pieces: a class implementing IExceptionHandler, AddExceptionHandler<T>() in services, and app.UseExceptionHandler() in the pipeline.

for a middle

Explain the chain: registration order, true stops it, false moves on, then the path, delegate or IProblemDetailsService fallback, and the startup error when none exists.

for a senior

Watch the singleton lifetime, set the status code before writing, keep handlers narrow and ordered, and know that handled exceptions go unlogged by default in ASP.NET Core 10.

for a principal

Decide how many handlers a service family needs, which exceptions are expected outcomes rather than errors, and how handlers stay consistent across teams.

## What IExceptionHandler is `IExceptionHandler` lives in `Microsoft.AspNetCore.Diagnostics` and arrived in **ASP.NET Core 8**. It gives the exception handler middleware a typed, injectable extension point, so the code that turns an exception into a response is a class you can unit test instead of a lambda buried in `Program.cs`. It has a single method: - `ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)` The `cancellationToken` the middleware passes is `HttpContext.RequestAborted`. ## Registering and switching it on Two lines are needed, and forgetting the second is the classic mistake: 1. `builder.Services.AddExceptionHandler<BookNotFoundExceptionHandler>();` registers the type as `IExceptionHandler`. The source is literally `services.AddSingleton<IExceptionHandler, T>()`, so the handler is a **singleton**. 2. `app.UseExceptionHandler();` adds the middleware. Handlers sitting in DI do nothing without it; the middleware resolves `IEnumerable<IExceptionHandler>` from the root provider once, when the pipeline is built. Because the handler is a singleton, constructor-inject only singletons (`IProblemDetailsService`, `ILogger<T>`, `TimeProvider`). For something scoped, such as a DbContext, resolve it from `httpContext.RequestServices` inside `TryHandleAsync`. ## What the middleware does around the chain When an exception escapes and the response has not started, the middleware: 1. clears the response and the selected endpoint; 2. stores `IExceptionHandlerFeature` and `IExceptionHandlerPathFeature`; 3. sets `Response.StatusCode` to 500, or to `StatusCodeSelector(exception)` if that option is set; 4. calls each `IExceptionHandler` **in registration order** until one returns `true`; 5. if none did, runs the fallback. The order is the order of the `AddExceptionHandler<T>()` calls. There is no matching on exception type: a handler that returns `true` for everything, registered first, hides every handler after it. Put narrow handlers (one exception type each) first and a catch-all last, or leave the catch-all to the fallback. ## Returning true or false | Return | Meaning | What happens next | |---|---|---| | `true` | "I wrote the response" | the chain stops; by default in ASP.NET Core 10 the middleware does not log the exception | | `false` | "not mine" | the next handler runs; after the last one, the fallback runs | Returning `true` without writing anything leaves the client with whatever the middleware set: an empty body with status 500 or the selected code. A handler that wants 404 or 409 must set `httpContext.Response.StatusCode` itself before writing, because the default ProblemDetails writer copies the response status into the body, not the other way round. ## The fallback when no handler says true - If `ExceptionHandlingPath` or the `ExceptionHandler` delegate is set (`UseExceptionHandler("/error")` or `UseExceptionHandler(errorApp => ...)`), that runs. - Otherwise the middleware calls `IProblemDetailsService.TryWriteAsync` with the exception, which needs `builder.Services.AddProblemDetails()`. - If neither exists, building the pipeline throws an `InvalidOperationException` saying that either `ExceptionHandlingPath` or `ExceptionHandler` must be set, or that `AddProblemDetails()` must be configured. The usual API setup is therefore `AddProblemDetails()`, one or more `AddExceptionHandler<T>()` calls and a bare `UseExceptionHandler()`. What the ProblemDetails body contains, and how to customise it, is a separate topic. ## A worked chain for the catalogue A public library catalogue API registers two narrow handlers and `AddProblemDetails()`: 1. A `BookNotFoundException` reaches `BookNotFoundExceptionHandler`, which sets 404, writes a ProblemDetails body and returns `true`; the second handler never runs. 2. A `CatalogueOfflineException` is refused by the first handler (`false`) and taken by `CatalogueOfflineExceptionHandler`, which sets 503 and returns `true`. 3. A `NullReferenceException` is refused by both, so the middleware's fallback asks `IProblemDetailsService` for a generic 500 body. The exception is logged, because no `IExceptionHandler` handled it. Design tips that follow from the mechanics: - Keep each handler to one exception family and one status, so ordering mistakes stay visible. - Return the result of `IProblemDetailsService.TryWriteAsync` instead of a hard-coded `true`: when the client accepts only HTML, no writer can answer and the next handler or fallback gets its turn. - Never put request-specific state in fields; one instance serves every request at once. ## Version notes - ASP.NET Core 8 introduced `IExceptionHandler` and `AddExceptionHandler<T>()`. - ASP.NET Core 9 added `StatusCodeSelector`. - ASP.NET Core 10 stopped logging exceptions that an `IExceptionHandler` handled; `SuppressDiagnosticsCallback` restores the old behaviour. This answer assumes ASP.NET Core 10.

  • Your IExceptionHandler needs the request's DbContext to record the failure; how do you get it?
    Not through the constructor: `AddExceptionHandler<T>()` registers the handler as a singleton, so a scoped DbContext injected there would be captured once and shared across requests. Resolve it per call with `httpContext.RequestServices.GetRequiredService<CatalogueDbContext>()`, or set `CreateScopeForErrors` if the failed request's own scope may be unusable.
  • When should an IExceptionHandler return true without being the last handler?
    Whenever it has written a complete response for an exception it owns. True stops the chain, so later handlers never see that exception. A handler should return false for exceptions it does not recognise and also when it could not write, for example when `IProblemDetailsService.TryWriteAsync` returns false because the client accepts only HTML.
  • Can an IExceptionHandler find out which endpoint and route values the failed request had?
    Yes. Before calling the handlers the middleware stores an `IExceptionHandlerFeature` in `httpContext.Features`, with `Error`, `Path`, `Endpoint` and `RouteValues` captured from the original request. The middleware then clears the endpoint on the context itself, so read the feature, not `httpContext.GetEndpoint()`.

A switchboard ringing extensions in the order they are listed: the call goes to each one until somebody picks up, and if nobody does it lands in the general voicemail. Nobody checks which extension is the best match for the caller.

  • AddExceptionHandler<T> registers the handler as scoped, so it can inject a DbContext directly.
  • The middleware picks the IExceptionHandler whose exception type matches best, like catch blocks.
  • Registering an IExceptionHandler is enough; app.UseExceptionHandler() is optional.
  • Returning false from TryHandleAsync makes the middleware rethrow the exception at once.
  • Returning true makes the middleware write a ProblemDetails body for you.

Assumes ASP.NET Core 10; IExceptionHandler arrived in ASP.NET Core 8, and since 10 an exception a handler handled is no longer logged by the middleware.