Cross.ErrorHandlers
7.4.0
See the version list below for details.
dotnet add package Cross.ErrorHandlers --version 7.4.0
NuGet\Install-Package Cross.ErrorHandlers -Version 7.4.0
<PackageReference Include="Cross.ErrorHandlers" Version="7.4.0" />
<PackageVersion Include="Cross.ErrorHandlers" Version="7.4.0" />
<PackageReference Include="Cross.ErrorHandlers" />
paket add Cross.ErrorHandlers --version 7.4.0
#r "nuget: Cross.ErrorHandlers, 7.4.0"
#:package Cross.ErrorHandlers@7.4.0
#addin nuget:?package=Cross.ErrorHandlers&version=7.4.0
#tool nuget:?package=Cross.ErrorHandlers&version=7.4.0
Cross.ErrorHandlers

A .NET library providing unified error handling for ASP.NET Core applications. The package implements middleware that catches exceptions and transforms them into standardized JSON responses with proper HTTP status codes.
Target frameworks: net6.0, net7.0, net8.0, net9.0, net10.0
Key Features
- Global exception handling middleware (
ErrorHandlerMiddleware) - Responses wrapped in
ApiEnvelopewith anerrorpayload (ErrorModel) - Built-in handling for FluentValidation
ValidationException,JsonException, and library-specific exception types - Request correlation ID (
X-Correlation-Idheader or generated GUID) - Configurable clearing of the
errorsdictionary viaClearStackTraceErrors(see below) - Optional
IInternalServerLoggerto customize how caught exceptions are logged
Purpose
Designed to streamline error handling across microservices and web applications while maintaining proper error tracking and debugging capabilities.
Install NuGet package
Install the package Cross.ErrorHandlers NuGet package into your ASP.NET Core project:
Install-Package Cross.ErrorHandlers
or
dotnet add package Cross.ErrorHandlers
Quick Start
- Register the middleware early in the pipeline (typically before other middleware that might throw):
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// ...
var app = builder.Build();
app.UseMiddleware<ErrorHandlerMiddleware>();
// Other middleware...
app.Run();
}
}
- The middleware will automatically catch exceptions and return standardized responses.
Error Response Format
Errors are serialized as camelCase JSON. The body is an ApiEnvelope object: the failure details live under error (ErrorModel).
{
"data": null,
"error": {
"correlationId": "00000000-0000-0000-0000-000000000000",
"code": "errorCode",
"subCode": null,
"message": "Error description",
"errors": {
"field1": ["Error message 1"],
"Exception": ["Full exception text when details are retained"]
}
}
}
subCode is set when a ConflictException carries a sub-code (via Data["SubCode"]).
Supported Exception Types
| Exception type | HTTP status | Error code (ErrorCodeEnum) |
|---|---|---|
ValidationException |
406 | InvalidParameters |
JsonException |
406 | InvalidParameters |
InvalidOperationException |
400 | InvalidOperation |
NotFoundException |
400 | NotFound |
ConflictException |
400 | Conflict |
BadRequestException |
400 | BadRequest |
NotAuthorizedException |
401 | NotAuthorized |
ForbiddenException |
403 | Forbidden |
IdentityUserManagerException |
500 | UnauthorizedClient |
HttpClientException |
400 | InvalidClient |
ImageNotFoundException |
400 | ImageNotFound |
Exception (default) |
500 | InternalServerError |
NotFoundException, HttpClientException, and ImageNotFoundException are not logged again by the middleware (treated as already expected or logged upstream). All other handled types follow the same logging path as in Custom exception logging: IInternalServerLogger from RequestServices when resolvable, otherwise ILogger<ErrorHandlerMiddleware>.
Configuration
ClearStackTraceErrors is read with IConfiguration.GetValue<bool>("ClearStackTraceErrors"). When true, the middleware replaces error.errors with an empty object for every response except those with status 406 (NotAcceptable), where validation/JSON error details are always kept. When the key is missing, the value defaults to false.
Example appsettings.json (omit the key or set false to keep exception detail entries in errors for non-406 responses):
{
"ClearStackTraceErrors": true // Set to false to include stack traces in responses
}
Set to false to keep the populated errors dictionary (e.g. exception details) on other status codes.
Correlation ID
- If the request includes a valid GUID in the
X-Correlation-Idheader, that value is used. - Otherwise a new GUID is generated.
- The value is set on the returned
error.correlationId.
Custom exception logging
Register an implementation of Cross.ErrorHandlers.Logging.IInternalServerLogger in DI. For each logged exception path, the middleware resolves IInternalServerLogger from HttpContext.RequestServices when that provider is non-null; otherwise it falls back to ILogger<ErrorHandlerMiddleware>.
Custom Exception Example
public class YourController : ControllerBase
{
[HttpGet]
public IActionResult Get(int id)
{
var item = _repository.GetById(id);
if (item == null)
throw new NotFoundException($"Item with id {id} not found");
return Ok(item);
}
}
Example response when the item is not found (shape and status as produced by the current middleware):
{
"data": null,
"error": {
"code": "NotFound",
"subCode": null,
"message": "Item with id 123 not found",
"correlationId": "7b2ab0e6-3c42-4488-a8b5-9b6d15b63e1a",
"errors": {
"Exception": ["NotFoundException: Item with id 123 not found"]
}
}
}
HTTP status for this case is 400 unless you change the middleware.
Issues and Pull Requests
Contributions are welcome. Please include tests with substantive changes.
Contributing
- Fork the repository on GitHub (creates a copy under your account).
- Clone your fork locally (
git clone https://github.com/<your-username>/Cross.ErrorHandlers.git). - Create a feature branch from the default branch (
git switch -c feature/amazing-feature). - Commit your changes (
git commit -m 'Add some amazing feature'). - Push the branch to your fork (
git push -u origin feature/amazing-feature). - Open a Pull Request from your fork’s feature branch into this repository’s default branch.
License
This project is licensed under the MIT License — see the LICENSE file for details.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. 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. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
- FluentValidation (>= 11.8.0)
- MediatR.Contracts (>= 2.0.1)
- Microsoft.AspNetCore.Http.Abstractions (>= 2.3.9)
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Configuration.Binder (>= 8.0.2)
- Microsoft.Extensions.DependencyInjection (>= 8.0.1)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.1)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.3)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Cross.ErrorHandlers:
| Package | Downloads |
|---|---|
|
Cross.Identity
Identity and authentication library for .NET: configurable flows (registration, login, forgot password, token, refresh), JWT, Argon2, email/SMS verification, process engine with JSON-defined flows. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 7.5.0 | 0 | 3/25/2026 |
| 7.4.0 | 132 | 3/21/2026 |
| 7.4.0-preview.12 | 29 | 3/21/2026 |
| 7.4.0-preview.11 | 31 | 3/21/2026 |
| 7.4.0-preview.10 | 35 | 3/21/2026 |
| 7.4.0-preview.9 | 36 | 3/21/2026 |
| 7.4.0-preview.8 | 34 | 3/21/2026 |
| 7.4.0-preview.7 | 35 | 3/21/2026 |
| 7.4.0-preview.6 | 29 | 3/21/2026 |
| 7.4.0-preview.5 | 31 | 3/20/2026 |
| 7.3.1-preview.3 | 0 | 3/25/2026 |
| 7.3.0 | 1,073 | 6/25/2025 |
| 7.3.0-preview.16 | 171 | 6/25/2025 |
| 7.3.0-preview.14 | 168 | 6/25/2025 |
| 7.3.0-preview.12 | 162 | 6/25/2025 |
| 7.3.0-preview.10 | 157 | 6/25/2025 |
| 7.3.0-preview.4 | 168 | 6/25/2025 |
| 7.2.0 | 11,522 | 7/24/2024 |
| 7.2.0-preview.4 | 105 | 7/24/2024 |
| 7.2.0-preview.3 | 120 | 7/24/2024 |
- Optional IInternalServerLogger in DI: middleware calls LogInternalServerError on your implementation when registered; otherwise falls back to ILogger<ErrorHandlerMiddleware>.
- Library targets net6.0, net7.0, net8.0, net9.0, net10.0 (previously net7.0 / net8.0 only).
- Replaced Microsoft.AspNetCore.Mvc.Core with Microsoft.AspNetCore.Http.Abstractions and explicit Microsoft.Extensions.* packages; FluentValidation updated to 11.12.0.
- Added Microsoft.SourceLink.GitHub for debugging (symbols).
- Packaged assemblies for net6.0, net9.0, net10.0; nuspec dependencies and copyright aligned with the project.
- README updated: ApiEnvelope / ErrorModel, features, configuration (ClearStackTraceErrors), correlation ID, exception table, custom logging.
- Extended middleware unit tests (correlation ID, ClearStackTraceErrors, IInternalServerLogger, HttpClientException paths, ConflictException); added ModelsTests for ApiEnvelope and ErrorModel.
- GitHub Actions: setup-dotnet installs SDK bands 6.0.x–10.0.x to match target frameworks.