The exception handler can use IStringLocalizer combined with the request's Accept-Language header (parsed by ASP.NET Core's built-in request localization middleware) to select and return an error message in the client's preferred language, mapping exception types or error codes to localized resource string keys rather than hardcoding English-only messages directly.
A globally-distributed SaaS API returns error messages in the client's browser-configured language by combining request localization middleware with a resource-file-backed error message lookup in its global exception handler.
Likely follow-ups
How does ASP.NET Core's request localization middleware determine the preferred language?
What's the maintenance overhead of keeping error message translations in sync across many languages?
Without any exception handling middleware configured, an unhandled exception propagates all the way up through Kestrel, resulting in either a bare 500 Internal Server Error with no body (in Production) or, if the developer exception page is active, a detailed HTML error page with the full stack trace -- neither is appropriate for a real production API, which is why configuring at least a basic UseExceptionHandler is considered essential baseline setup.
Example
// With NO exception handling middleware configured:
// An unhandled exception results in a generic 500 with an empty or minimal body
// -- no consistent JSON error format, no logging guarantee, no safe error message
Real-world example
A newly bootstrapped API prototype that skipped configuring UseExceptionHandler entirely is caught in code review before its first production deployment, since every unhandled exception would otherwise return an unhelpful bare 500 response.
Likely follow-ups
What's the minimum viable exception handling setup for a new ASP.NET Core API?
Why does Kestrel itself not provide a default JSON error format?
Global Exception Handling & MiddlewareASP.NET Core Middleware & Request Pipeline
Using WebApplicationFactory<T> to spin up an in-memory test server, create a test-only endpoint or use an existing one that deliberately throws a known exception, then assert on the actual HTTP response's status code and JSON body shape returned by the real exception handling middleware, verifying the full pipeline behavior rather than just unit testing the handler class in isolation.
[Fact]
public async Task NotFoundException_Returns404WithProblemDetails() {
var client = _factory.CreateClient();
var response = await client.GetAsync("/api/products/99999");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
var problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
Assert.Equal("Resource not found", problem.Title);
}
Real-world example
A team adds an integration test suite specifically verifying error response shapes for each custom exception type, catching a regression where a refactor accidentally changed the JSON field name from 'title' to 'Title', breaking client-side error parsing.
Likely follow-ups
How does WebApplicationFactory differ from a full end-to-end test against a real deployed instance?
What's the value of testing the actual pipeline versus just unit testing the handler class directly?
Testing ASP.NET Core ApplicationsGlobal Exception Handling & Middleware
Transient errors (network timeouts, temporary service unavailability, rate limit responses) are typically identified by specific exception types or HTTP status codes (like 503, 429) known to represent temporary conditions, appropriate for retry logic with backoff -- permanent errors (like 400 Bad Request indicating malformed input, or 404 indicating a genuinely missing resource) should fail immediately without retrying, since retrying an inherently unrecoverable error just wastes time and resources without any chance of success.
var retryPolicy = Policy
.Handle<HttpRequestException>()
.OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.ServiceUnavailable || (int)r.StatusCode == 429)
.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)));
// 400/404 responses are NOT retried -- they're permanent failures
Real-world example
A payment processing integration correctly retries a 503 Service Unavailable response from the payment gateway up to three times with backoff, but immediately surfaces a 400 Bad Request (indicating a genuinely malformed payment request) to the caller without any wasted retry attempts.
Likely follow-ups
How do you classify a timeout -- transient or permanent?
What's the risk of retrying a non-idempotent operation without careful consideration?
A circuit breaker (implementable via Polly's CircuitBreakerPolicy) tracks consecutive failures against a downstream dependency, and once a failure threshold is exceeded, 'opens' the circuit -- immediately failing subsequent calls without even attempting them for a cooldown period, preventing the calling application from wasting resources on calls almost certain to fail and giving the struggling downstream dependency breathing room to recover, rather than the calling service continuing to hammer it during an outage.
var circuitBreaker = Policy
.Handle<HttpRequestException>()
.CircuitBreakerAsync(exceptionsAllowedBeforeBreaking: 5, durationOfBreak: TimeSpan.FromSeconds(30));
try {
await circuitBreaker.ExecuteAsync(() => CallDownstreamServiceAsync());
} catch (BrokenCircuitException) {
// circuit is open -- fail fast without even attempting the call
return Results.Problem("Service temporarily unavailable", statusCode: 503);
}
Real-world example
An order-processing service wraps its calls to a flaky inventory-checking dependency in a circuit breaker, so after 5 consecutive failures it stops attempting new calls entirely for 30 seconds, immediately returning a 503 to callers instead of piling up slow, doomed-to-fail requests during the dependency's outage.
Likely follow-ups
How does a circuit breaker's half-open state work to test if the dependency has recovered?
How would you combine circuit breaking with retry logic without them conflicting?