Advertisement
Advanced ASP.NET Core, Error Handling

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

Short answer

Once HttpResponse.HasStarted is true (typically after the first write to the response body, common in streaming scenarios), you can no longer modify the response status code or headers -- exception handling middleware must check HasStarted and, if true, can only log the error…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Once HttpResponse.HasStarted is true (typically after the first write to the response body, common in streaming scenarios), you can no longer modify the response status code or headers -- 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;
    }
    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 (since headers were already sent) -- the team adds thorough upfront validation to catch as many failure conditions as possible before streaming begins.
Likely 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?
Related topics