ErrorOrX 2.1.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package ErrorOrX --version 2.1.1
                    
NuGet\Install-Package ErrorOrX -Version 2.1.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="ErrorOrX" Version="2.1.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ErrorOrX" Version="2.1.1" />
                    
Directory.Packages.props
<PackageReference Include="ErrorOrX" />
                    
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 ErrorOrX --version 2.1.1
                    
#r "nuget: ErrorOrX, 2.1.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 ErrorOrX@2.1.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=ErrorOrX&version=2.1.1
                    
Install as a Cake Addin
#tool nuget:?package=ErrorOrX&version=2.1.1
                    
Install as a Cake Tool

ErrorOrX

NuGet NuGet Downloads License: MIT

A discriminated union type for .NET with source-generated ASP.NET Core Minimal API integration. One package, zero boilerplate, full AOT support.

Installation

dotnet add package ErrorOrX

Quick Start

Program.cs

var builder = WebApplication.CreateSlimBuilder(args);
builder.Services.AddOpenApi();

var app = builder.Build();
app.MapOpenApi();
app.MapErrorOrEndpoints();  // Auto-registers all endpoints
app.Run();

Define Endpoints

using ErrorOr;

public static class TodoApi
{
    [Get("/todos")]
    public static ErrorOr<List<Todo>> GetAll(ITodoService svc)
        => svc.GetAll();

    [Get("/todos/{id}")]
    public static ErrorOr<Todo> GetById(int id, ITodoService svc)
        => svc.GetById(id) is { } todo
            ? todo
            : Error.NotFound("Todo.NotFound", $"Todo {id} not found");

    [Post("/todos")]
    public static ErrorOr<Todo> Create(CreateTodoRequest req, ITodoService svc)
    {
        if (string.IsNullOrWhiteSpace(req.Title))
            return Error.Validation("Todo.InvalidTitle", "Title is required");

        return svc.Create(req);  // Returns 201 Created with Location header
    }

    [Delete("/todos/{id}")]
    public static ErrorOr<Deleted> Delete(int id, ITodoService svc)
        => svc.Delete(id) ? Result.Deleted : Error.NotFound("Todo.NotFound", $"Todo {id} not found");
}

ErrorOr Fundamentals

Creating Values and Errors

// Success - implicit conversion
ErrorOr<int> result = 42;

// Errors
ErrorOr<User> notFound = Error.NotFound("User.NotFound", "User not found");
ErrorOr<User> validation = Error.Validation("User.InvalidEmail", "Invalid email format");

// Multiple errors
ErrorOr<User> errors = new List<Error>
{
    Error.Validation("User.InvalidName", "Name is required"),
    Error.Validation("User.InvalidEmail", "Email is invalid")
};

Checking Results

if (result.IsError)
{
    foreach (var error in result.Errors)
        Console.WriteLine($"{error.Code}: {error.Description}");
}
else
{
    Console.WriteLine(result.Value);
}

Built-in Result Types

ErrorOr<Deleted> DeleteUser(int id) => Result.Deleted;   // 204 No Content
ErrorOr<Updated> UpdateUser(int id) => Result.Updated;   // 204 No Content
ErrorOr<Created> CreateUser()       => Result.Created;   // 201 Created
ErrorOr<Success> DoSomething()      => Result.Success;   // 200 OK

Error Types and HTTP Mapping

Error Factory HTTP Status TypedResult
Error.Validation() 400 ValidationProblem
Error.Unauthorized() 401 UnauthorizedHttpResult
Error.Forbidden() 403 ForbidHttpResult
Error.NotFound() 404 NotFound<ProblemDetails>
Error.Conflict() 409 Conflict<ProblemDetails>
Error.Failure() 500 InternalServerError<ProblemDetails>
Error.Unexpected() 500 InternalServerError<ProblemDetails>

Middleware Attribute Support

The generator detects BCL middleware attributes and emits corresponding fluent calls:

[Post("/admin/users")]
[Authorize("Admin")]
[EnableRateLimiting("fixed")]
public static ErrorOr<User> CreateAdmin(CreateUserRequest req)
{
    // Generated code includes:
    // .RequireAuthorization("Admin")
    // .RequireRateLimiting("fixed")
}
Attribute Generated Call
[Authorize] .RequireAuthorization()
[Authorize("Policy")] .RequireAuthorization("Policy")
[AllowAnonymous] .AllowAnonymous()
[EnableRateLimiting("policy")] .RequireRateLimiting("policy")
[DisableRateLimiting] .DisableRateLimiting()
[OutputCache] .CacheOutput()
[OutputCache(PolicyName = "x")] .CacheOutput("x")
[EnableCors("policy")] .RequireCors("policy")
[DisableCors] .DisableCors()

Fluent API

Chain operations with railway-oriented programming:

// Then - chain dependent operations
ErrorOr<Order> result = ValidateOrder(request)
    .Then(order => CheckInventory(order))
    .Then(order => ProcessPayment(order))
    .Then(order => CreateShipment(order));

// Async chains
var result = await GetUserAsync(id)
    .ThenAsync(user => ValidateAsync(user))
    .ThenAsync(user => EnrichAsync(user));

// Else - provide fallbacks
User user = GetUser(id).Else(User.Guest);
User user = GetUser(id).Else(errors => HandleErrors(errors));

// Match - handle both cases
string message = GetUser(id).Match(
    onValue: user => $"Found: {user.Name}",
    onError: errors => $"Error: {errors.First().Description}"
);

// Switch - side effects
GetUser(id).Switch(
    onValue: user => SendEmail(user),
    onError: errors => LogErrors(errors)
);

Endpoint Attributes

[Get("/path")]              // HTTP GET
[Post("/path")]             // HTTP POST
[Put("/path")]              // HTTP PUT
[Delete("/path")]           // HTTP DELETE
[Patch("/path")]            // HTTP PATCH

// Route parameters
[Get("/users/{id}")]
public static ErrorOr<User> Get(int id) { }

// Query parameters (automatically bound)
[Get("/users")]
public static ErrorOr<List<User>> Search(int page = 1, string? search = null) { }

// Request body (automatically bound for POST/PUT/PATCH)
[Post("/users")]
public static ErrorOr<User> Create(CreateUserRequest request) { }

// Async endpoints
[Get("/users/{id}")]
public static Task<ErrorOr<User>> GetAsync(int id, CancellationToken ct) { }

Native AOT Support

ErrorOr is fully compatible with Native AOT. The source generator produces reflection-free code that works with PublishAot=true.

<PropertyGroup>
    <PublishAot>true</PublishAot>
</PropertyGroup>

For AOT JSON serialization, register your types:

[JsonSerializable(typeof(Todo))]
[JsonSerializable(typeof(List<Todo>))]
public partial class AppJsonContext : JsonSerializerContext { }

// In Program.cs
builder.Services.ConfigureHttpJsonOptions(options =>
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));

Best Practices

Domain-Specific Errors

public static class UserErrors
{
    public static Error NotFound(int id) =>
        Error.NotFound("User.NotFound", $"User {id} not found");

    public static Error DuplicateEmail(string email) =>
        Error.Conflict("User.DuplicateEmail", $"Email '{email}' already exists");
}

// Usage
return UserErrors.NotFound(id);

Aggregate Validation Errors

public static ErrorOr<ValidatedRequest> Validate(CreateUserRequest request)
{
    var errors = new List<Error>();

    if (string.IsNullOrWhiteSpace(request.Name))
        errors.Add(Error.Validation("User.Name.Required", "Name is required"));

    if (string.IsNullOrWhiteSpace(request.Email))
        errors.Add(Error.Validation("User.Email.Required", "Email is required"));

    return errors.Count > 0 ? errors : new ValidatedRequest(request);
}

Keep Endpoints Thin

// Delegate to services
[Post("/orders")]
public static ErrorOr<Order> Create(CreateOrderRequest request, IOrderService service)
    => service.CreateOrder(request);

Documentation

Contributing

Contributions are welcome. Please open an issue to discuss proposed changes before submitting a pull request.

License

MIT License.

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 was computed.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  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 (1)

Showing the top 1 NuGet packages that depend on ErrorOrX:

Package Downloads
ErrorOrX.Generators

Roslyn source generator for ASP.NET Core Minimal API integration with ErrorOrX. Auto-generates MapErrorOrEndpoints() with typed Results unions for OpenAPI, smart parameter binding (body/route/query/service inference), middleware attribute emission, and JSON serialization context. Full Native AOT support.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.6.3 31 1/18/2026
2.6.2 26 1/18/2026
2.6.1 29 1/18/2026
2.6.0 38 1/15/2026
2.5.0 40 1/14/2026
2.4.0 39 1/13/2026
2.3.1 45 1/13/2026
2.3.0 38 1/13/2026
2.2.1 49 1/12/2026
2.1.1 50 1/12/2026