Advertisement
Advanced ASP.NET Core, Error Handling

How would you design exception handling to support internationalized (localized) error messages returned to different clients in their preferred language?

Short answer

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…

Save ASP.NET Core mock interview
Advertisement
AModel answer
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.
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"],
        _ => 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 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?
Related topics