Back to results for “Error Handling”
.NET › Global Exception Handling & Middleware

How would you design exception handling middleware to support internationalized (localized) error messages returned to clients in different languages?

Advanced

Answer

The exception handler can use IStringLocalizer (or a similar localization service) 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 in exception messages.
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct) {
    var localizer = context.RequestServices.GetRequiredService<IStringLocalizer<ErrorMessages>>();
    var message = exception switch {
        NotFoundException => localizer["ResourceNotFound"],
        ValidationException => localizer["ValidationFailed"],
        _ => localizer["UnexpectedError"]
    };
    await context.Response.WriteAsJsonAsync(new { message = message.Value }, ct);
    return true;
}
Real-world example A globally-distributed SaaS API returns error messages in the client's browser-configured language (French, Japanese, Spanish) by combining request localization middleware with a resource-file-backed error message lookup in its global exception handler.

Common 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?