skip to content

In ASP.NET Core 10, how does the exception handler middleware choose the response status code, and in which cases does it rethrow instead of answering?

level: seniorimportance: should knowfreq 30%

answer

  1. Response.Clear() wipes the endpoint's status
  2. default 500 unless StatusCodeSelector
  3. Response.HasStarted means log and rethrow
  4. unstarted 404 wrapped in InvalidOperationException
  5. AllowStatusCode404Response, client abort 499

basics

~20 s

After clearing the response, the middleware sets 500 or the value of StatusCodeSelector, and a handler may overwrite it. It rethrows when the response had already started, when its own handler throws, or when the handler path leaves an unstarted 404 without AllowStatusCode404Response.

solid answer

~40 s

When an exception reaches `UseExceptionHandler`, the middleware first checks for a client abort (an `OperationCanceledException` or `IOException` with `RequestAborted` signalled): it logs at Debug, sets 499 if it can and returns. If `Response.HasStarted`, it logs a warning and the exception and rethrows, because headers are gone. Otherwise it calls `Response.Clear()`, which discards any status the endpoint set, then sets `StatusCodeSelector?.Invoke(exception) ?? 500` (`StatusCodeSelector` arrived in ASP.NET Core 9). An `IExceptionHandler` may change the status before writing. If the error path or delegate ends with an unstarted 404 and neither `StatusCodeSelector` nor `AllowStatusCode404Response` is set, the middleware assumes a misconfigured path and throws an `InvalidOperationException` wrapping the original. If the handler itself throws, the original exception is rethrown.

code

csharp · 13 lines
csharp
builder.Services.AddProblemDetails();
var app = builder.Build();

app.UseExceptionHandler(new ExceptionHandlerOptions
{
    // ASP.NET Core 9+: pick the status before the ProblemDetails fallback writes the body.
    StatusCodeSelector = exception => exception switch
    {
        BookNotFoundException => StatusCodes.Status404NotFound,
        CatalogueUnavailableException => StatusCodes.Status503ServiceUnavailable,
        _ => StatusCodes.Status500InternalServerError
    }
});

go deeper

for a junior

Remember that the exception handler sends 500 by default and cannot help once the response has started.

for a middle

Explain Response.Clear(), the StatusCodeSelector default, and how an IExceptionHandler can override the status before writing.

for a senior

Diagnose the 404 rethrow from a mismatched error path, the 499 client-abort path and mid-stream failures, and choose StatusCodeSelector over scattered status code logic.

for a principal

Decide which failures may be streamed and which must stay mappable to a clean status, and keep status mapping centralised for every team.

## The order of decisions The exception handler middleware takes the same steps for every exception that escapes the rest of the pipeline. Knowing the order explains most surprises in production. 1. **Client abort.** If the exception is an `OperationCanceledException` or an `IOException` and `HttpContext.RequestAborted` is cancelled, the client went away. The middleware logs "The request was aborted by the client." at Debug, sets `StatusCodes.Status499ClientClosedRequest` if the response has not started, and returns. No handler runs and nothing is rethrown. 2. **Response already started.** If `Response.HasStarted` is true, status and headers are already on the wire. The middleware logs the warning "The response has already started, the error handler will not be executed.", logs the exception and **rethrows** it; the server then aborts the response. 3. **Reset.** It calls `Response.Clear()`, which resets the status code, headers and buffered body, and clears the selected endpoint and route values so a re-execution routes afresh. 4. **Pick a status.** It sets `Response.StatusCode` to `StatusCodeSelector(exception)` when that option is set, otherwise to **500**. 5. **Handle.** It calls each `IExceptionHandler` in registration order, then the error path, delegate or `IProblemDetailsService` fallback. 6. **Decide the outcome**, including the 404 rule below. ## StatusCodeSelector `ExceptionHandlerOptions.StatusCodeSelector` is a `Func<Exception, int>?` added in **ASP.NET Core 9**. It maps exception types to statuses in one place, for example `BookNotFoundException` to 404 and `CatalogueUnavailableException` to 503. Without it every exception starts at 500. The value lands on `Response.StatusCode` before any handler runs, so: - the ProblemDetails fallback writes it into the body's `status`; - an `IExceptionHandler` sees it and may still overwrite it; - the status the endpoint set before throwing never survives, because step 3 cleared it. ## The 404 rule A common misconfiguration is an `ExceptionHandlingPath` that matches no endpoint, for example an error endpoint mapped with `MapGet` while the failed request was a POST. Re-execution then finds nothing, routing leaves an **empty 404**, and the client would receive a misleading "not found" for a server fault. The middleware guards against this: after handling, if - nothing counted as handling it (no `IExceptionHandler` returned true, the path or delegate did not start a response, and the ProblemDetails fallback wrote nothing), - the status is 404, - `StatusCodeSelector` is null, and - `AllowStatusCode404Response` is false (its default), it logs the original exception and throws an `InvalidOperationException` whose message says the handler "produced a 404 status response", with the original as the inner exception. | Situation | Result | |---|---| | `IExceptionHandler` sets 404 and returns true | 404 sent, no rethrow | | `StatusCodeSelector` maps the exception to 404 | 404 sent, no rethrow | | error path writes a 404 page body | 404 sent, no rethrow | | error path matches nothing, empty 404 | `InvalidOperationException` rethrown | | same, with `AllowStatusCode404Response = true` | empty 404 sent | Set `AllowStatusCode404Response` only when an empty 404 from the error path is truly intended. ## When the handler itself fails If an `IExceptionHandler`, the error endpoint or the delegate throws, the middleware logs "An exception was thrown attempting to execute the error handler.", logs the original exception and rethrows the **original**. The request path and, with `CreateScopeForErrors`, the DI scope are restored first. ## Reading the outcome in telemetry Each path leaves a different trace, which helps when a client reports a strange status: - client abort: a Debug "request aborted" entry and a 499 in access logs; - started response: the `ResponseStarted` warning followed by the `UnhandledException` error; - 404 rethrow: the original exception logged, then the server's own unhandled-exception entry carrying the `InvalidOperationException`; - handler failure: the "error handler" exception entry, then the original exception. ## Practical consequences - Do not rely on the status an endpoint set before throwing; map it with `StatusCodeSelector` or set it in a handler. - Streaming endpoints that fail mid-body cannot be turned into clean errors here; the middleware can only log and rethrow. - A handler that wants 404 should set the status and return true, which never triggers the rethrow. - The response also gets `Cache-Control: no-cache,no-store`, `Pragma: no-cache` and `Expires: -1`, and any `ETag` is removed, so caches never keep the error.

  • Why does an error path that renders a 404 page not trigger the InvalidOperationException rethrow?
    The rethrow fires only when nothing counted as handling the exception. For a path or delegate, the middleware counts it as handled once the response has started, which happens when the error page writes its body. Only an error path that leaves an unstarted, bodiless 404, typically because no endpoint matched, is treated as a misconfiguration.
  • Why map statuses with StatusCodeSelector rather than inside each IExceptionHandler?
    The selector runs once, before any handler, so the mapping lives in one function and the `IProblemDetailsService` fallback picks the status up without a custom handler. Handlers can still overwrite it for special cases. A configured selector also disables the empty-404 rethrow, because the middleware then treats a 404 as deliberate.

  • The exception handler can still turn a half-streamed 200 into a 500 ProblemDetails.
  • StatusCodeSelector already existed in ASP.NET Core 8 next to IExceptionHandler.
  • An error path that matches no endpoint simply sends the client an empty 404.
  • The status an endpoint set before throwing is kept in the error response.
  • When the client disconnects, the middleware runs every handler and logs an error.

Assumes ASP.NET Core 10; StatusCodeSelector was added in ASP.NET Core 9, and before it every exception started at status 500.