Siemens.AspNet.ErrorHandling 2.0.1

Prefix Reserved
This package has a SemVer 2.0.0 package version: 2.0.1+2.
dotnet add package Siemens.AspNet.ErrorHandling --version 2.0.1                
NuGet\Install-Package Siemens.AspNet.ErrorHandling -Version 2.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Siemens.AspNet.ErrorHandling" Version="2.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Siemens.AspNet.ErrorHandling --version 2.0.1                
#r "nuget: Siemens.AspNet.ErrorHandling, 2.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Siemens.AspNet.ErrorHandling as a Cake Addin
#addin nuget:?package=Siemens.AspNet.ErrorHandling&version=2.0.1

// Install Siemens.AspNet.ErrorHandling as a Cake Tool
#tool nuget:?package=Siemens.AspNet.ErrorHandling&version=2.0.1                

Siemens.AspNet.ErrorHandling

The Siemens.AspNet.ErrorHandling package provides middleware and services for handling errors in ASP.NET Core applications. It includes features for translating error messages based on the "Accepted Languages" header, making it easier to build multilingual applications with standardized error responses. The package is designed to work seamlessly with its companion package, Siemens.AspNet.ErrorHandling.Contracts Link to Documentation, which defines the core error handling models and base classes like ProblemDetails and ValidationProblemDetails.

By using RFC 7807, we ensure that error responses are consistent, easily interpretable by clients, and capable of conveying rich, structured information about errors. This approach enhances interoperability and helps developers diagnose issues more effectively.

Installation

To install the package, use the following NuGet command:

dotnet add package Siemens.AspNet.ErrorHandling

Installation

To install the Siemens.AspNet.ErrorHandling package, you can use the NuGet Package Manager Console or the .NET CLI:

NuGet Package Manager Console
Install-Package Siemens.AspNet.ErrorHandling
.NET CLI
dotnet add package Siemens.AspNet.ErrorHandling

Getting Started

1. Register the Middleware and Services

In your ASP.NET Core application, you need to register the error handling services in the Startup.cs or Program.cs file.

Dotnet 7
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Register the error handling services
        services.AddErrorHandling();

        // Other service registrations...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Add the error handling middleware to the request pipeline
        app.UseErrorHandlingMiddleware();

        // Other middleware...
    }
}
Dotnet 8 or higher
var builder = WebApplication.CreateBuilder(args);
// Register the error handling services
builder.Services.AddErrorHandling();
// Other service registrations...

var app = builder.Build();
// Add the error handling middleware to the request pipeline
app.UseErrorHandling();
// Other middleware...

app.Run();
2. Use Translations (Optional)

The Siemens.AspNet.ErrorHandling package offers robust support for translating error messages based on the client's "Accepted Languages" header. This is achieved through a pattern-based approach to localization keys, allowing for consistent and easily maintainable translations across your application.

Language Handling

The Siemens.AspNet.ErrorHandling package automatically selects the appropriate language for error messages based on the client's "Accepted-Languages" HTTP header. Here’s how the language handling works:

  • <b>Language Selection:</b> The package reads the "Accepted-Languages" header from the client's request to determine the preferred language. This header can contain one or more language codes, and the package will attempt to match these codes with your available translation files.
  • <b>Default Language:</b> If the client's preferred language is not available or not specified, the package defaults to English (en).
  • <b>Fallback Mechanism:</b> The package leverages the CultureInfo class to handle language fallbacks. If a specific language variant (e.g., de-DE for German in Germany) is not available, the package will automatically fall back to the parent language (e.g., de for general German). This ensures that even if a specific translation is missing, the client still receives an error message in a related language.

For example, if the client requests de-DE (German for Germany) but only de.json is available, the package will use the translations from de.json. This fallback mechanism ensures that users receive the most appropriate localized content available.

Translation Files

To manage translations effectively, the Siemens.AspNet.ErrorHandling package uses JSON files for storing localized error messages. Follow these guidelines to set up your translation files:

  • <b>File Format</b>: The translation files are in JSON format, where each file corresponds to a specific language.
  • <b>Folder Organization</b>: Place your translation files in a dedicated folder like "Translations" or "ErrorTranslations". This helps you easily locate and manage your translation files.
  • <b>File Naming Convention</b>: Name your translation files based on the language code, such as de.json for German or en.json for English. This ensures clarity and consistency in your localization resources.

By organizing your translation files in this manner, you can maintain a clean and efficient structure that makes it easy to manage and update your localized content.

Translation Key Pattern

The translation keys for error messages follow a specific pattern, making it straightforward to manage translations for different exception types and scenarios. The pattern is as follows:

  • Title Translation Key: {Caller}.{ExceptionName}.Title.{TheExceptionTitle}
  • Details Translation Key: {Caller}.{ExceptionName}.Details.{TheExceptionTitle}
  • Errors Translation Key: {Caller}.{ExceptionName}.Errors.{TheExceptionTitle}.{ErrorKey}

Variables:

  • {Caller} - refers to the class or method that raised the exception.
  • {ExceptionName} - is the name of the exception class.
  • {TheExceptionTitle} - is a key representing the specific error context.
  • {ErrorKey} - represents the specific validation or error message key.
Example

Consider a scenario where you have a ValidationDetailsException in a class or method named MyAwesomeClass. The translation keys might look like this:

{
  "MyAwesomeClass.ValidationDetailsException.Title.AUTH_TITLE_KEY": "This is my translated title",
  "MyAwesomeClass.ValidationDetailsException.Details.AUTH_TITLE_KEY": "This is my translated details",
  "MyAwesomeClass.ValidationDetailsException.Errors.AUTH_TITLE_KEY.Name.Name is required.": "This is my translated errors for name 1",
  "MyAwesomeClass.ValidationDetailsException.Errors.AUTH_TITLE_KEY.Name.Name must be at least 3 characters long.": "This is my translated errors for name 2",
  "MyAwesomeClass.ValidationDetailsException.Errors.AUTH_TITLE_KEY.Email.Email is not in a valid format.": "This is my translated errors for email"
}

This example shows how to throw an error in your c# code.

     var errors = new Dictionary<string, string[]>
                        { 
                            { "Name", new[] { "Name is required.", "Name must be at least 3 characters long." } },
                            { "Email", new[] { "Email is not in a valid format." } }
                        };
     throw new ValidationDetailsException("AUTH_TITLE_KEY", "AUTH_DETAILS_KEY", errors);
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.0.1 92 11/27/2024
2.0.0 74 11/19/2024
1.0.0 243 10/13/2024