Multi-language global/custom Exception handling in .NET Core 2.1 Web API

Viewed 823

I'm currently adding some middlewares on my .NET Core 2.1 Web API project to integrate multi-language support and a "as much as possible" REST/RFC compliant Exception handling mechanism.

About multi-language, I started with the built-in IStringLocalizer<T> class, Localization middleware and service registration inside the ConfigureServices and Configure methods in Startup class and then creating the culture' specific RESX files.

For Exception handling, I also used the app.UseExceptionHandler() built-in middleware as follows:

public static class ExceptionHandler
{
    public static void UseGlobalExceptionHandler(this IApplicationBuilder app)
    {
        app.UseExceptionHandler(config =>
        {
            config.Run(async context =>
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.ContentType = "application/json";

                var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                if (errorFeature != null)
                {
                    Exception ex = errorFeature.Error;
                    ErrorDetails errorDetails = new ErrorDetails
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = ex.Message
                    };

                    Log.Error(ex, "Request error {ErrorDetails}", errorDetails);
                    await context.Response.WriteAsync(errorDetails.ToString());
                }
            });
        });
    }
}

Now I'd like to make the multi-language support and the Exception handling work together, to customize the language of the error details text.

Is there a best practice or a "standard" well known approach with those built-in .NET Core objects?

Also some side questions:

  1. I didn't actually really understand what's the difference (the benefits) between built-in global Exception handling and the possibility to create a custom Exception middleware.
  2. About RFC compliance on Exception handling, I red this article. Should I use the built-in ProblemDetails .NET Core object or can I use my ErrorDetails class as well?
0 Answers
Related