CSharpEssentials.Errors 6.5.1

dotnet add package CSharpEssentials.Errors --version 6.5.1
                    
NuGet\Install-Package CSharpEssentials.Errors -Version 6.5.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="CSharpEssentials.Errors" Version="6.5.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CSharpEssentials.Errors" Version="6.5.1" />
                    
Directory.Packages.props
<PackageReference Include="CSharpEssentials.Errors" />
                    
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 CSharpEssentials.Errors --version 6.5.1
                    
#r "nuget: CSharpEssentials.Errors, 6.5.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.
#:package CSharpEssentials.Errors@6.5.1
                    
#: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=CSharpEssentials.Errors&version=6.5.1
                    
Install as a Cake Addin
#tool nuget:?package=CSharpEssentials.Errors&version=6.5.1
                    
Install as a Cake Tool

CSharpEssentials.Errors

Structured, type-safe error handling for .NET. Errors are data, not exceptions.

Features

  • Error Struct: Value-type error with code, description, type, and metadata.
  • Standard Error Types: Failure, Validation, NotFound, Conflict, Unauthorized, Forbidden, Unexpected. ErrorType also has an Unknown member, which has no factory method.
  • ErrorMetadata: Attach contextual data to errors fluently.
  • Exception Bridge: Convert exceptions to Error or throw DomainException / EnhancedValidationException.
  • HTTP Mapping: Built-in conversion between ErrorType and HTTP status codes.

Targets net11.0, net10.0, net9.0 and netstandard2.1. Depends on CSharpEssentials.Core and CSharpEssentials.Enums.

Installation

dotnet add package CSharpEssentials.Errors

Usage

Creating Errors

using CSharpEssentials.Errors;

Error notFound = Error.NotFound("User.NotFound", "User was not found.");
Error validation = Error.Validation("Email.Invalid", "Email format is invalid.");
Error conflict = Error.Conflict("User.Duplicate", "User already exists.");
Error failure = Error.Failure("Payment.Failed", "Payment was rejected.");
Error forbidden = Error.Forbidden("Order.Forbidden", "You cannot cancel this order.");
Error unauthorized = Error.Unauthorized("Token.Expired", "The token has expired.");
Error unexpected = Error.Unexpected("Db.Down", "The database is unreachable.");

Every factory takes code, description and an optional ErrorMetadata, and all three have defaults: Error.NotFound() has the code NotFound and the description A 'Not Found' error has occurred. An Error exposes Code, Description, Type, NumericType (the int value of Type) and Metadata (null when none was given). It implements IError, and two errors are equal when type, code, description and metadata entries are equal.

Error Metadata

Error withMeta = Error.NotFound(
    "User.NotFound",
    "User was not found.",
    new ErrorMetadata()
        .AddMetadata("TraceId", Guid.NewGuid().ToString())
        .AddMetadata("RequestPath", "/api/users/123"));

ErrorMetadata is a Dictionary<string, object?>. AddMetadata keeps the existing value when the key is already present. AddStackTrace, AddException and AddExceptionDetailed add well-known keys (stackTrace, exception, exceptionType, exceptionStackTrace, exceptionMessage, innerException), Combine merges another instance without overwriting, and CreateEmpty, CreateWithStackTrace, CreateWithException and CreateWithExceptionDetailed are the static counterparts.

Combining Errors

Error a = Error.Validation("Name.Empty", "Name is required.");
Error b = Error.Validation("Email.Invalid", "Email is invalid.");

Error[] combined = a + b;

Error[] many = Error.CreateMany(a, b);                          // params of Error or of Error collections
Error[] single = a;                                             // implicit Error -> Error[]

Converting from Exceptions

try { /* ... */ }
catch (Exception ex)
{
    Error error = Error.Exception(ex);
}

Error.Exception(ex) uses the exception type name as the code, the exception message as the description and ErrorType.Failure. The metadata carries exceptionType, exceptionStackTrace, exceptionMessage and, when there is one, a nested innerException. Overloads take an explicit code, an explicit code and description, an ErrorType and extra ErrorMetadata:

Error custom = Error.Exception("Orders.SaveFailed", "The order could not be saved.", ex, ErrorType.Unexpected);

Domain Exceptions

using CSharpEssentials.Errors;
using CSharpEssentials.Exceptions;

Error error = Error.Validation("Order.Invalid", "Total must be greater than zero.");
throw new DomainException(error);

DomainException and EnhancedValidationException live in the CSharpEssentials.Exceptions namespace of this package; see the exception types.

HTTP Status Mapping

int status = ErrorType.NotFound.ToHttpStatusCode();     // 404
ErrorType type = 401.ToErrorType();                      // Unauthorized
ErrorType HTTP status
Validation 400
Unauthorized 401
Forbidden 403
NotFound 404
Conflict 409
Failure, Unexpected, Unknown 500

ToErrorType is the reverse for 400, 401, 403, 404, 409 and 500 (Failure); every other status code gives Unexpected.

Domain-Specific Error Hierarchies

Error is a value type (readonly record struct) and cannot be subclassed. The idiomatic way to build domain-specific, typed error hierarchies is to group static factory methods in a dedicated class per aggregate or bounded context:

using CSharpEssentials.Errors;

// Organize errors by domain aggregate
public static class UserErrors
{
    public static Error NotFound(Guid id) =>
        Error.NotFound("User.NotFound", $"User '{id}' was not found.");

    public static readonly Error AlreadyExists =
        Error.Conflict("User.AlreadyExists", "A user with that email already exists.");

    public static Error InvalidAge(int age) =>
        Error.Validation("User.InvalidAge", $"Age {age} is not allowed; must be 18 or older.");

    public static readonly Error Unauthorized =
        Error.Unauthorized("User.Unauthorized", "You are not authorized to perform this action.");
}

public static class OrderErrors
{
    public static readonly Error EmptyCart =
        Error.Validation("Order.EmptyCart", "Cannot place an order with an empty cart.");

    public static Error InsufficientFunds(decimal required, decimal available) =>
        Error.Failure(
            "Order.InsufficientFunds",
            $"Payment requires {required:C} but only {available:C} is available.",
            new ErrorMetadata().AddMetadata("Required", required).AddMetadata("Available", available));
}

Usage with Result:

using CSharpEssentials.ResultPattern; // CSharpEssentials.Results package

public Result<User> FindUser(Guid id)
{
    User? user = _repo.Find(id);
    if (user is null)
        return UserErrors.NotFound(id);   // implicit Error → Result<User>

    return user;
}

public Result PlaceOrder(Cart cart, decimal balance)
{
    if (cart.IsEmpty)
        return OrderErrors.EmptyCart;

    if (balance < cart.Total)
        return OrderErrors.InsufficientFunds(cart.Total, balance);

    return Result.Success();
}

This pattern provides discoverability (IDE autocomplete per domain), type-safe error codes, and centralised descriptions, all without inheritance.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  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 was computed.  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 was computed.  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.  net11.0 is compatible. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (8)

Showing the top 5 NuGet packages that depend on CSharpEssentials.Errors:

Package Downloads
CSharpEssentials.Results

Result pattern implementation for functional error handling in C#. Provides Result<T> and Result types for railway-oriented programming, eliminating exceptions for expected failures. Foundation for functional programming patterns and robust error handling.

CSharpEssentials

A comprehensive C# library enhancing functional programming capabilities with type-safe monads (Maybe, Result), discriminated unions (Any), and robust error handling. Features include: domain-driven design support, enhanced Entity Framework integration, testable time management, JSON utilities, and LINQ extensions. Built for modern C# development with focus on maintainability, testability, and functional programming principles.

CSharpEssentials.AspNetCore

A comprehensive ASP.NET Core library that enhances functional programming capabilities in web applications. Features include API versioning, global exception handling with enhanced problem details, enum binding and wire formats, model validation, optimized JSON handling, and seamless integration with CSharpEssentials core functional patterns (Result, Maybe, Rule Engine). Perfect for building robust, maintainable, and type-safe web APIs following functional programming principles. OpenAPI documents come from CSharpEssentials.AspNetCore.OpenApi or CSharpEssentials.AspNetCore.Swashbuckle.

CSharpEssentials.Maybe

Maybe monad implementation with LINQ support for functional programming in C#. Provides type-safe null handling, eliminates null reference exceptions, and enables functional composition. Essential for functional programming patterns and safe value handling.

CSharpEssentials.Http

HttpClient extensions that bridge HTTP calls to the Result pattern. Provides GetFromJsonAsResultAsync, PostAsJsonAsResultAsync, status code mapping, and Polly resilience integration.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
6.5.1 0 10/10/2026
6.5.0 0 10/9/2026
6.4.0 25 10/9/2026
6.3.0 64 10/8/2026
6.2.0 130 10/8/2026
6.1.0 154 10/7/2026
6.0.0 161 10/7/2026
5.2.1 191 10/7/2026
5.2.0 213 10/7/2026
5.1.0 224 10/7/2026
5.0.0 290 10/6/2026
4.1.0 307 10/6/2026
4.0.0 379 10/5/2026
3.2.3 631 5/31/2026
3.2.2 500 5/31/2026
3.2.1 457 5/31/2026
3.2.0 450 5/30/2026
3.1.0 420 5/27/2026
3.0.8 427 5/20/2026
3.0.7 408 5/20/2026
Loading failed