.NET › Global Exception Handling & Middleware

How do you handle exceptions that occur during response streaming, after the response has already partially started sending to the client?

Advanced

Answer

Once HttpResponse.HasStarted is true (typically after the first write to the response body, common in streaming scenarios like Server-Sent Events or large file downloads), you can no longer modify the response status code or headers -- an exception occurring at this point can't be gracefully converted into a different error response shape, so exception handling middleware must check HasStarted and, if true, can only log the error and abruptly terminate the connection, making it critical to validate and prepare everything possible before any response writing begins.
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct) {
    if (context.Response.HasStarted) {
        _logger.LogError(exception, "Exception after response started, cannot modify response");
        return true;  // acknowledge as 'handled' but can't change what's already been sent
    }
    context.Response.StatusCode = 500;
    await context.Response.WriteAsJsonAsync(new { title = "An error occurred" }, ct);
    return true;
}
Real-world example A large file-export endpoint that fails midway through streaming can't return a clean error response to the client (since headers were already sent) -- the team adds thorough upfront validation to catch as many failure conditions as possible before streaming begins, minimizing this unavoidable limitation's impact.

Common follow-ups: How would a client detect and handle a connection that was abruptly terminated mid-stream?;What upfront validation strategies minimize the risk of mid-stream failures?