Error handling and response commitment
Error handling and response commitment
A response is committed when its headers have been sent. Before commitment, error middleware may replace a failed response with a controlled status and body. After commitment, changing the status or headers is no longer safe; the server may have to terminate the response or connection. Design error handling for both phases.
UseExceptionHandler can catch exceptions from downstream middleware and endpoints. In production, return a redacted error representation, for example ProblemDetails, and keep diagnostic details in appropriately protected logs. AddProblemDetails registers services used by error handling and related features; UseStatusCodePages handles suitable empty error-status responses, not thrown exceptions. A 404 is not necessarily an exception. HttpResponse.HasStarted indicates commitment; Response.StartAsync explicitly starts a response. OnStarting runs before headers are sent. If an exception occurs after response start, error middleware cannot re-execute a replacement response; avoid promising a second 500. Before response start, path-based exception handling can re-execute the request with its original method; middleware must tolerate re-entry, avoid repeating side effects and handle the error endpoint without disclosing exception details. This is different from retrying a failed business operation. Client behavior depends on protocol and failure point. Do not expose stack traces, paths, credentials or sensitive request data. Treat cancellation and expected domain failures separately from unexpected exceptions.
Baseline: .NET 10 / C# 14. Examples are independent Web SDK projects, with source files shown below or in the companion fixture. All expected outputs are reasoned, not executed. Run only in an isolated environment with an approved SDK, no real data, no launch profile and no external network. The finite loopback host uses ephemeral data protection keys and a test-only cookie container. No production security configuration is implied.
Return a redacted problem before commitment
A deliberately thrown synthetic exception is handled before headers are sent. Assert status, media type and absence of the private marker.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddProblemDetails();await using var app = builder.Build();app.UseExceptionHandler(error => error.Run(async ctx =>{ await Results.Problem(statusCode: 500, title: "Unexpected error").ExecuteAsync(ctx);}));app.MapGet("/fail", (Func<IResult>)(() => throw new InvalidOperationException("synthetic-private-marker")));using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/fail", deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check((int)response.StatusCode == 500 && response.Content.Headers.ContentType?.MediaType == "application/problem+json", "problem result"); Check(body.Contains("Unexpected error") && !body.Contains("synthetic-private-marker"), "redacted body"); Console.WriteLine("500 / redacted problem");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
500 / redacted problemThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Give an empty 404 a body
Status code pages handles an empty 404, whereas exception handling responds to an exception. A successful response is unchanged.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.UseStatusCodePages("text/plain", "Status: {0}");app.MapGet("/ready", () => "ready");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var missing = await client.GetAsync("/unknown", deadline.Token); using var good = await client.GetAsync("/ready", deadline.Token); Check(missing.StatusCode == HttpStatusCode.NotFound && (await missing.Content.ReadAsStringAsync(deadline.Token)) == "Status: 404", "status page"); Check(good.IsSuccessStatusCode && (await good.Content.ReadAsStringAsync(deadline.Token)) == "ready", "success unchanged"); Console.WriteLine("404 / ready");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
404 / readyThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Observe response commitment explicitly
This fixture does not intentionally break a connection. It observes HasStarted before and after StartAsync, making the boundary deterministic without assuming client behavior on a truncated response.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/commit", async (HttpContext ctx) =>{ bool before = ctx.Response.HasStarted; ctx.Response.ContentType = "text/plain"; await ctx.Response.StartAsync(ctx.RequestAborted); bool after = ctx.Response.HasStarted; await ctx.Response.WriteAsync($"{before} / {after}", ctx.RequestAborted);});using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/commit", deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.IsSuccessStatusCode && body == "False / True", "commit boundary"); Console.WriteLine("commit boundary"); Console.WriteLine(body);}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
commit boundaryFalse / TrueThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Common mistakes and limitations
Do not catch an exception after commitment and pretend a different status reached the client. Never show developer exception pages on production endpoints. A status-code page is not a substitute for exception middleware. A redacted public message still needs appropriate internal observability; this lab clears log providers only to keep output predictable.
Practice and recap
A streaming endpoint writes one chunk and then fails. Compare the correct recovery options with a handler that fails before its first write. Describe client-side verification without assuming the exact network exception.
Use the fixture assertions to verify the behavior after modification. Explain the observed result before moving to the next lesson.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Error handling and response commitment — knowledge check
Apply the lesson concepts to the following scenarios.
What does HasStarted indicate?
When can exception middleware replace a response?
Which middleware addresses suitable empty error status responses?
What should a public 500 response avoid?
What is guaranteed when streaming fails after commitment?