Siemens.AspNet.ErrorHandling.Contracts 7.6.32

Prefix Reserved
This package has a SemVer 2.0.0 package version: 7.6.32+1.
dotnet add package Siemens.AspNet.ErrorHandling.Contracts --version 7.6.32
                    
NuGet\Install-Package Siemens.AspNet.ErrorHandling.Contracts -Version 7.6.32
                    
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.Contracts" Version="7.6.32" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Siemens.AspNet.ErrorHandling.Contracts" Version="7.6.32" />
                    
Directory.Packages.props
<PackageReference Include="Siemens.AspNet.ErrorHandling.Contracts" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Siemens.AspNet.ErrorHandling.Contracts --version 7.6.32
                    
#r "nuget: Siemens.AspNet.ErrorHandling.Contracts, 7.6.32"
                    
#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.
#:package Siemens.AspNet.ErrorHandling.Contracts@7.6.32
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Siemens.AspNet.ErrorHandling.Contracts&version=7.6.32
                    
Install as a Cake Addin
#tool nuget:?package=Siemens.AspNet.ErrorHandling.Contracts&version=7.6.32
                    
Install as a Cake Tool

Siemens.AspNet.ErrorHandling.Contracts

This package provides the essential data types and base classes used for error handling in ASP.NET Core applications. These classes are designed to standardize error responses and ensure consistency across different layers of your application.

We adhere to the RFC 7807 specification, which defines a standardized format for representing problem details in HTTP APIs. 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

.NET CLI

dotnet add package Siemens.AspNet.ErrorHandling.Contracts

NuGet Package Manager Console

Install-Package Siemens.AspNet.ErrorHandling.Contracts

  • Siemens.AspNet.ErrorHandling:
    • Middleware for ASP.NET Core error handling.
    • Includes generic handlers suitable for scenarios like AWS Lambda.
    • Already includes Siemens.AspNet.ErrorHandling.Contracts.

๐Ÿšง Important Usage Recommendations

ProblemDetailsException or ValidationProblemDetailsException

ProblemDetailsException and ValidationProblemDetailsException serve as base classes (or โ€œroot classesโ€) for more specialized exceptions. While theyโ€™re provided by the framework to help shape error responses according to the RFC 7807: Problem Details for HTTP APIs specification, they are * not* intended for direct, everyday use in your application. Instead, you should:

  1. Extend:
    If you need custom error-handling logic, create your own exception classes that inherit from these root classes. This approach allows you to add or override properties and methods, ensuring your exceptions contain meaningful context about the errors they represent.

  2. Maintain clarity and structure:
    Using derived classes helps keep your code organized and intention-revealing. By naming your custom exceptions clearly (e.g., InvalidOrderException, UserRegistrationFailedException), you communicate the specific error context and keep your codebase easier to maintain.

  3. Promote flexibility:
    As your application grows, you may need additional logic, fields, or response behavior for certain types of errors. Inheriting from these root classes gives you the freedom to evolve your exceptions over time without disrupting the broader error-handling infrastructure.



๐ŸŽฏ Error Enrichment

The Siemens.AspNet.ErrorHandling.Contracts package provides a powerful Error Enrichment system that allows you to add custom metadata to error responses and logs before they are sent to clients or written to your logging infrastructure.

Overview

The enrichment system uses the Strategy Pattern and provides two main enrichment points:

  1. Error Response Enrichment - Enrich ProblemDetails objects before they are written to the HTTP response
  2. Error Log Enrichment - Enrich ErrorLogInfo objects before they are serialized and logged

Core Interfaces

IErrorResponseEnricher

Implement this interface to add custom metadata to error responses sent to clients:

public interface IErrorResponseEnricher
{
    Task<ProblemDetails> EnrichAsync(ProblemDetails problemDetails,
                                     HttpCallInfos httpCallInfos,
                                     Exception exception);
}
IErrorLogEnricher

Implement this interface to add custom metadata to error logs:

public interface IErrorLogEnricher
{
    Task<ErrorLogInfo> EnrichAsync(ErrorLogInfo errorLogInfo,
                                   HttpCallInfos httpCallInfos,
                                   Exception exception);
}

Strategy Interfaces

The enrichment system uses strategies to coordinate multiple enrichers:

  • IErrorResponseEnrichmentStrategy - Coordinates all response enrichers
  • IErrorLogEnrichmentStrategy - Coordinates all log enrichers

The default implementations apply all registered enrichers sequentially and include built-in error handling to ensure enrichment failures don't break the main error handling flow.

Example: Response Enricher

public class CorrelationIdEnricher : IErrorResponseEnricher
{
    public Task<ProblemDetails> EnrichAsync(ProblemDetails problemDetails,
                                           HttpCallInfos httpCallInfos,
                                           Exception exception)
    {
        // Add correlation ID for distributed tracing
        problemDetails.Extensions["correlationId"] = httpCallInfos.TraceId;
        problemDetails.Extensions["timestamp"] = DateTime.UtcNow.ToString("o");
        
        return Task.FromResult(problemDetails);
    }
}

// Register in DI container
services.AddSingleton<IErrorResponseEnricher, CorrelationIdEnricher>();

Example: Log Enricher with Async Operations

public class UserContextEnricher(IUserService userService) : IErrorLogEnricher
{
    public async Task<ErrorLogInfo> EnrichAsync(ErrorLogInfo errorLogInfo,
                                                HttpCallInfos httpCallInfos,
                                                Exception exception)
    {
        // Perform async operations to gather additional context
        var userContext = await userService.GetUserContextAsync(httpCallInfos.UserId);
        
        return errorLogInfo with
        {
            Extensions = errorLogInfo.Extensions
                .Add("userId", userContext.UserId)
                .Add("userRole", userContext.Role)
                .Add("tenantId", userContext.TenantId)
        };
    }
}

// Register in DI container
services.AddSingleton<IErrorLogEnricher, UserContextEnricher>();

Key Features

  • โœ… Async Support - All enrichment methods are async, enabling database lookups, API calls, or other I/O operations
  • โœ… Strategy Pattern - Centralized control over enrichment flow, execution order, and error handling
  • โœ… Immutable Design - Enrichers return new instances, promoting functional programming patterns
  • โœ… Automatic Registration - The Siemens.AspNet.ErrorHandling package automatically discovers and applies all registered enrichers
  • โœ… Failure Isolation - Enrichment failures are caught and logged but don't break the error handling pipeline
  • โœ… Multiple Enrichers - Register as many enrichers as needed; they execute in registration order

Use Cases

  • Add correlation/trace IDs for distributed tracing
  • Include environment information (dev/staging/production)
  • Add tenant or organization context in multi-tenant applications
  • Include user information for audit trails
  • Add custom metadata for monitoring and alerting systems
  • Enrich with feature flags or A/B test information
  • Add performance metrics or request timing data

For implementation details and integration examples, see the Siemens.AspNet.ErrorHandling Documentation.


๐Ÿ“‘ Exception Classes Overview

๐Ÿ”น ProblemDetails-Based Exceptions

300 Ambiguous - AmbigousDetailsException

Equivalent to HTTP status 300. <see cref="F:System.Net.HttpStatusCode.Ambiguous" /> indicates that the requested information has multiple representations. The default action is to treat this status as a redirect and follow the contents of the Location header associated with this response. Ambiguous is a synonym for MultipleChoices.


300 MultipleChoices - MultipleChoicesDetailsException

Equivalent to HTTP status 300. <see cref="F:System.Net.HttpStatusCode.MultipleChoices" /> indicates that the requested information has multiple representations. The default action is to treat this status as a redirect and follow the contents of the Location header associated with this response. MultipleChoices is a synonym for Ambiguous.


301 Moved - MovedDetailsException

Equivalent to HTTP status 301. <see cref="F:System.Net.HttpStatusCode.Moved" /> indicates that the requested information has been moved to the URI specified in the Location header. The default action when this status is received is to follow the Location header associated with the response. When the original request method was POST, the redirected request will use the GET method. Moved is a synonym for MovedPermanently.


301 MovedPermanently - MovedPermanentlyDetailsException

Equivalent to HTTP status 301. <see cref="F:System.Net.HttpStatusCode.MovedPermanently" /> indicates that the requested information has been moved to the URI specified in the Location header. The default action when this status is received is to follow the Location header associated with the response. MovedPermanently is a synonym for Moved.


302 Found - FoundDetailsException

Equivalent to HTTP status 302. <see cref="F:System.Net.HttpStatusCode.Found" /> indicates that the requested information is located at the URI specified in the Location header. The default action when this status is received is to follow the Location header associated with the response. When the original request method was POST, the redirected request will use the GET method. Found is a synonym for Redirect.


302 Redirect - RedirectDetailsException

Equivalent to HTTP status 302. <see cref="F:System.Net.HttpStatusCode.Redirect" /> indicates that the requested information is located at the URI specified in the Location header. The default action when this status is received is to follow the Location header associated with the response. When the original request method was POST, the redirected request will use the GET method. Redirect is a synonym for Found.


303 RedirectMethod - RedirectMethodDetailsException

Equivalent to HTTP status 303. <see cref="F:System.Net.HttpStatusCode.RedirectMethod" /> automatically redirects the client to the URI specified in the Location header as the result of a POST. The request to the resource specified by the Location header will be made with a GET. RedirectMethod is a synonym for SeeOther.


303 SeeOther - SeeOtherDetailsException

Equivalent to HTTP status 303. <see cref="F:System.Net.HttpStatusCode.SeeOther" /> automatically redirects the client to the URI specified in the Location header as the result of a POST. The request to the resource specified by the Location header will be made with a GET. SeeOther is a synonym for RedirectMethod.


304 NotModified - NotModifiedDetailsException

Equivalent to HTTP status 304. <see cref="F:System.Net.HttpStatusCode.NotModified" /> indicates that the client's cached copy is up to date. The contents of the resource are not transferred.


305 UseProxy - UseProxyDetailsException

Equivalent to HTTP status 305. <see cref="F:System.Net.HttpStatusCode.UseProxy" /> indicates that the request should use the proxy server at the URI specified in the Location header.


306 Unused - UnusedDetailsException

Equivalent to HTTP status 306. <see cref="F:System.Net.HttpStatusCode.Unused" /> is a proposed extension to the HTTP/1.1 specification that is not fully specified.


307 RedirectKeepVerb - RedirectKeepVerbDetailsException

Equivalent to HTTP status 307. <see cref="F:System.Net.HttpStatusCode.RedirectKeepVerb" /> indicates that the request information is located at the URI specified in the Location header. The default action when this status is received is to follow the Location header associated with the response. When the original request method was POST, the redirected request will also use the POST method. RedirectKeepVerb is a synonym for TemporaryRedirect.


307 TemporaryRedirect - TemporaryRedirectDetailsException

Equivalent to HTTP status 307. <see cref="F:System.Net.HttpStatusCode.TemporaryRedirect" /> indicates that the request information is located at the URI specified in the Location header. The default action when this status is received is to follow the Location header associated with the response. When the original request method was POST, the redirected request will also use the POST method. TemporaryRedirect is a synonym for RedirectKeepVerb.


308 PermanentRedirect - PermanentRedirectDetailsException

Equivalent to HTTP status 308. <see cref="F:System.Net.HttpStatusCode.PermanentRedirect" /> indicates that the request information is located at the URI specified in the Location header. The default action when this status is received is to follow the Location header associated with the response. When the original request method was POST, the redirected request will also use the POST method.


400 BadRequest - BadRequestDetailsException

HINT: In case you have validation information, use BadRequestValidationDetailsException.

Equivalent to HTTP status 400. <see cref="F:System.Net.HttpStatusCode.BadRequest" /> indicates that the request could not be understood by the server. <see cref="F:System.Net.HttpStatusCode.BadRequest" /> is sent when no other error is applicable, or if the exact error is unknown or does not have its own error code.


401 Unauthorized - UnauthorizedDetailsException

Equivalent to HTTP status 401. <see cref="F:System.Net.HttpStatusCode.Unauthorized" /> indicates that the requested resource requires authentication. The WWW-Authenticate header contains the details of how to perform the authentication.


402 PaymentRequired - PaymentRequiredDetailsException

Equivalent to HTTP status 402. <see cref="F:System.Net.HttpStatusCode.PaymentRequired" /> is reserved for future use.


403 Forbidden - ForbiddenDetailsException

Equivalent to HTTP status 403. <see cref="F:System.Net.HttpStatusCode.Forbidden" /> indicates that the server refuses to fulfill the request.


404 NotFound - NotFoundDetailsException

Equivalent to HTTP status 404. <see cref="F:System.Net.HttpStatusCode.NotFound" /> indicates that the requested resource does not exist on the server.


405 MethodNotAllowed - MethodNotAllowedDetailsException

Equivalent to HTTP status 405. <see cref="F:System.Net.HttpStatusCode.MethodNotAllowed" /> indicates that the request method (POST or GET) is not allowed on the requested resource.


406 NotAcceptable - NotAcceptableDetailsException

Equivalent to HTTP status 406. <see cref="F:System.Net.HttpStatusCode.NotAcceptable" /> indicates that the client has indicated with Accept headers that it will not accept any of the available representations of the resource.


407 ProxyAuthenticationRequired - ProxyAuthenticationRequiredDetailsException

Equivalent to HTTP status 407. <see cref="F:System.Net.HttpStatusCode.ProxyAuthenticationRequired" /> indicates that the requested proxy requires authentication. The Proxy-authenticate header contains the details of how to perform the authentication.


408 RequestTimeout - RequestTimeoutDetailsException

Equivalent to HTTP status 408. <see cref="F:System.Net.HttpStatusCode.RequestTimeout" /> indicates that the client did not send a request within the time the server was expecting the request.


409 Conflict - ConflictDetailsException

Equivalent to HTTP status 409. <see cref="F:System.Net.HttpStatusCode.Conflict" /> indicates that the request could not be carried out because of a conflict on the server.


410 Gone - GoneDetailsException

Equivalent to HTTP status 410. <see cref="F:System.Net.HttpStatusCode.Gone" /> indicates that the requested resource is no longer available.


411 LengthRequired - LengthRequiredDetailsException