Siemens.AspNet.ErrorHandling.Contracts
7.6.32
Prefix Reserved
dotnet add package Siemens.AspNet.ErrorHandling.Contracts --version 7.6.32
NuGet\Install-Package Siemens.AspNet.ErrorHandling.Contracts -Version 7.6.32
<PackageReference Include="Siemens.AspNet.ErrorHandling.Contracts" Version="7.6.32" />
<PackageVersion Include="Siemens.AspNet.ErrorHandling.Contracts" Version="7.6.32" />
<PackageReference Include="Siemens.AspNet.ErrorHandling.Contracts" />
paket add Siemens.AspNet.ErrorHandling.Contracts --version 7.6.32
#r "nuget: Siemens.AspNet.ErrorHandling.Contracts, 7.6.32"
#:package Siemens.AspNet.ErrorHandling.Contracts@7.6.32
#addin nuget:?package=Siemens.AspNet.ErrorHandling.Contracts&version=7.6.32
#tool nuget:?package=Siemens.AspNet.ErrorHandling.Contracts&version=7.6.32
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
๐ Related Packages
- 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:
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.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.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:
- Error Response Enrichment - Enrich
ProblemDetailsobjects before they are written to the HTTP response - Error Log Enrichment - Enrich
ErrorLogInfoobjects 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 enrichersIErrorLogEnrichmentStrategy- 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.ErrorHandlingpackage 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.