--- name: dotnet-result-pattern description: "Implements the Result pattern for explicit error handling without exceptions. Provides Result, Result, and Error types for clean, predictable control flow in domain-driven applications." version: 1.0.0 language: C# framework: .NET 8+ pattern: Railway-Oriented Programming --- # Result Pattern Implementation ## Overview The Result pattern provides explicit error handling without exceptions: - **No exceptions for business errors** - Exceptions for truly exceptional cases only - **Explicit success/failure** - Compiler forces handling of both cases - **Composable errors** - Chain operations, fail fast - **Self-documenting** - Method signatures show possible outcomes ## Quick Reference | Type | Purpose | Usage | |------|---------|-------| | `Result` | Operation without return value | Update, Delete operations | | `Result` | Operation with return value | Create, Get operations | | `Error` | Error information | Code + Description | --- ## Implementation Structure ``` /Domain/Abstractions/ ├── Result.cs # Result and Result ├── Error.cs # Error record └── ValidationResult.cs # Multiple errors support ``` --- ## Template: Core Result Types ```csharp // src/{name}.domain/Abstractions/Error.cs namespace {name}.domain.abstractions; /// /// Represents an error with a code and description /// public record Error(string Code, string Description) { /// /// Represents no error (success state) /// public static readonly Error None = new(string.Empty, string.Empty); /// /// Represents a null value error /// public static readonly Error NullValue = new( "Error.NullValue", "A null value was provided"); /// /// Creates an error from an exception /// public static Error FromException(Exception exception) => new( "Error.Exception", exception.Message); /// /// Implicit conversion to string (returns Code) /// public static implicit operator string(Error error) => error.Code; public override string ToString() => Code; } ``` ```csharp // src/{name}.domain/Abstractions/Result.cs namespace {name}.domain.abstractions; /// /// Represents the outcome of an operation that doesn't return a value /// public class Result { protected Result(bool isSuccess, Error error) { if (isSuccess && error != Error.None) { throw new InvalidOperationException( "Cannot create successful result with an error"); } if (!isSuccess && error == Error.None) { throw new InvalidOperationException( "Cannot create failed result without an error"); } IsSuccess = isSuccess; Error = error; } public bool IsSuccess { get; } public bool IsFailure => !IsSuccess; public Error Error { get; } // ═══════════════════════════════════════════════════════════════ // FACTORY METHODS // ═══════════════════════════════════════════════════════════════ /// /// Creates a successful result /// public static Result Success() => new(true, Error.None); /// /// Creates a failed result with the specified error /// public static Result Failure(Error error) => new(false, error); /// /// Creates a successful result with a value /// public static Result Success(TValue value) => new(value, true, Error.None); /// /// Creates a failed result with the specified error /// public static Result Failure(Error error) => new(default, false, error); /// /// Creates a result based on a condition /// public static Result Create(bool condition, Error error) => condition ? Success() : Failure(error); /// /// Creates a result based on a condition with a value /// public static Result Create(TValue? value, Error error) => value is not null ? Success(value) : Failure(error); } /// /// Represents the outcome of an operation that returns a value /// public class Result : Result { private readonly TValue? _value; protected internal Result(TValue? value, bool isSuccess, Error error) : base(isSuccess, error) { _value = value; } /// /// Gets the value if successful, throws if failed /// public TValue Value => IsSuccess ? _value! : throw new InvalidOperationException( $"Cannot access value of a failed result. Error: {Error.Code}"); /// /// Implicit conversion from value to successful Result /// public static implicit operator Result(TValue? value) => value is not null ? Success(value) : Failure(Error.NullValue); /// /// Implicit conversion from Error to failed Result /// public static implicit operator Result(Error error) => Failure(error); } ``` --- ## Template: Result Extensions (Functional Operations) ```csharp // src/{name}.domain/Abstractions/ResultExtensions.cs namespace {name}.domain.abstractions; public static class ResultExtensions { // ═══════════════════════════════════════════════════════════════ // MAP: Transform success value // ═══════════════════════════════════════════════════════════════ /// /// Transforms the value if successful, preserves error if failed /// public static Result Map( this Result result, Func mapper) { return result.IsSuccess ? Result.Success(mapper(result.Value)) : Result.Failure(result.Error); } /// /// Async version of Map /// public static async Task> Map( this Task> resultTask, Func mapper) { var result = await resultTask; return result.Map(mapper); } // ═══════════════════════════════════════════════════════════════ // BIND: Chain operations that return Result // ═══════════════════════════════════════════════════════════════ /// /// Chains another Result-returning operation if successful /// public static Result Bind( this Result result, Func> binder) { return result.IsSuccess ? binder(result.Value) : Result.Failure(result.Error); } /// /// Async version of Bind /// public static async Task> Bind( this Result result, Func>> binder) { return result.IsSuccess ? await binder(result.Value) : Result.Failure(result.Error); } /// /// Async version of Bind for Task results /// public static async Task> Bind( this Task> resultTask, Func> binder) { var result = await resultTask; return result.Bind(binder); } /// /// Fully async Bind /// public static async Task> Bind( this Task> resultTask, Func>> binder) { var result = await resultTask; return await result.Bind(binder); } // ═══════════════════════════════════════════════════════════════ // TAP: Execute side effect without changing result // ═══════════════════════════════════════════════════════════════ /// /// Executes an action if successful, returns original result /// public static Result Tap( this Result result, Action action) { if (result.IsSuccess) { action(result.Value); } return result; } /// /// Async version of Tap /// public static async Task> Tap( this Result result, Func action) { if (result.IsSuccess) { await action(result.Value); } return result; } // ═══════════════════════════════════════════════════════════════ // MATCH: Pattern match on result // ═══════════════════════════════════════════════════════════════ /// /// Executes success or failure function based on result state /// public static TOut Match( this Result result, Func onSuccess, Func onFailure) { return result.IsSuccess ? onSuccess(result.Value) : onFailure(result.Error); } /// /// Async version of Match /// public static async Task Match( this Task> resultTask, Func onSuccess, Func onFailure) { var result = await resultTask; return result.Match(onSuccess, onFailure); } // ═══════════════════════════════════════════════════════════════ // ENSURE: Add validation to existing result // ═══════════════════════════════════════════════════════════════ /// /// Validates the value and fails if predicate returns false /// public static Result Ensure( this Result result, Func predicate, Error error) { if (result.IsFailure) { return result; } return predicate(result.Value) ? result : Result.Failure(error); } /// /// Async version of Ensure /// public static async Task> Ensure( this Result result, Func> predicate, Error error) { if (result.IsFailure) { return result; } return await predicate(result.Value) ? result : Result.Failure(error); } // ═══════════════════════════════════════════════════════════════ // COMBINE: Combine multiple results // ═══════════════════════════════════════════════════════════════ /// /// Combines multiple results, returning first failure or success /// public static Result Combine(params Result[] results) { foreach (var result in results) { if (result.IsFailure) { return result; } } return Result.Success(); } /// /// Combines multiple results with values /// public static Result<(T1, T2)> Combine( Result result1, Result result2) { if (result1.IsFailure) return Result.Failure<(T1, T2)>(result1.Error); if (result2.IsFailure) return Result.Failure<(T1, T2)>(result2.Error); return Result.Success((result1.Value, result2.Value)); } /// /// Combines three results with values /// public static Result<(T1, T2, T3)> Combine( Result result1, Result result2, Result result3) { if (result1.IsFailure) return Result.Failure<(T1, T2, T3)>(result1.Error); if (result2.IsFailure) return Result.Failure<(T1, T2, T3)>(result2.Error); if (result3.IsFailure) return Result.Failure<(T1, T2, T3)>(result3.Error); return Result.Success((result1.Value, result2.Value, result3.Value)); } // ═══════════════════════════════════════════════════════════════ // GET VALUE OR DEFAULT // ═══════════════════════════════════════════════════════════════ /// /// Returns the value if successful, or default value if failed /// public static T GetValueOrDefault( this Result result, T defaultValue = default!) { return result.IsSuccess ? result.Value : defaultValue; } /// /// Returns the value if successful, or result of factory if failed /// public static T GetValueOrDefault( this Result result, Func defaultFactory) { return result.IsSuccess ? result.Value : defaultFactory(); } } ``` --- ## Template: Validation Result (Multiple Errors) ```csharp // src/{name}.domain/Abstractions/ValidationResult.cs namespace {name}.domain.abstractions; /// /// Result that can contain multiple validation errors /// public sealed class ValidationResult : Result, IValidationResult { private ValidationResult(Error[] errors) : base(false, IValidationResult.ValidationError) { Errors = errors; } public Error[] Errors { get; } public static ValidationResult WithErrors(Error[] errors) => new(errors); } /// /// Validation result with a value /// public sealed class ValidationResult : Result, IValidationResult { private ValidationResult(Error[] errors) : base(default, false, IValidationResult.ValidationError) { Errors = errors; } public Error[] Errors { get; } public static ValidationResult WithErrors(Error[] errors) => new(errors); } /// /// Marker interface for validation results /// public interface IValidationResult { public static readonly Error ValidationError = new( "Validation.Error", "One or more validation errors occurred"); Error[] Errors { get; } } ``` --- ## Usage Examples ### Basic Usage in Domain Entity ```csharp public sealed class User : Entity { public static Result Create(string email, string name) { // Validate email var emailResult = Email.Create(email); if (emailResult.IsFailure) { return Result.Failure(emailResult.Error); } // Validate name if (string.IsNullOrWhiteSpace(name)) { return Result.Failure(UserErrors.NameRequired); } if (name.Length > 100) { return Result.Failure(UserErrors.NameTooLong); } var user = new User(Guid.NewGuid(), emailResult.Value, name); return Result.Success(user); } public Result UpdateName(string name) { if (string.IsNullOrWhiteSpace(name)) { return Result.Failure(UserErrors.NameRequired); } Name = name; return Result.Success(); } } ``` ### Usage in Command Handler ```csharp internal sealed class CreateUserCommandHandler : ICommandHandler { private readonly IUserRepository _userRepository; private readonly IUnitOfWork _unitOfWork; public async Task> Handle( CreateUserCommand request, CancellationToken cancellationToken) { // Check if user exists var existingUser = await _userRepository .GetByEmailAsync(request.Email, cancellationToken); if (existingUser is not null) { return Result.Failure(UserErrors.EmailAlreadyExists); } // Create user using factory method var userResult = User.Create(request.Email, request.Name); if (userResult.IsFailure) { return Result.Failure(userResult.Error); } _userRepository.Add(userResult.Value); await _unitOfWork.SaveChangesAsync(cancellationToken); return userResult.Value.Id; } } ``` ### Chaining with Bind ```csharp public async Task> PlaceOrder( Guid userId, CreateOrderRequest request, CancellationToken ct) { return await GetUser(userId, ct) .Bind(user => ValidateUserCanOrder(user)) .Bind(user => CreateOrder(user, request)) .Bind(order => ProcessPayment(order, ct)) .Bind(order => SendConfirmation(order, ct)); } ``` ### Using Match in Controller ```csharp [HttpPost] public async Task Create( [FromBody] CreateUserRequest request, CancellationToken ct) { var command = new CreateUserCommand(request.Email, request.Name); var result = await _sender.Send(command, ct); return result.Match( onSuccess: id => CreatedAtAction(nameof(GetById), new { id }, id), onFailure: error => error.Code switch { "User.EmailExists" => Conflict(error), "User.NotFound" => NotFound(error), _ => BadRequest(error) }); } ``` ### Combining Multiple Results ```csharp public Result CreateOrder( CreateOrderRequest request) { // Validate all fields var customerResult = CustomerId.Create(request.CustomerId); var addressResult = Address.Create(request.Street, request.City); var amountResult = Money.Create(request.Amount); // Combine - returns first failure var combinedResult = ResultExtensions.Combine( customerResult, addressResult, amountResult); if (combinedResult.IsFailure) { return Result.Failure(combinedResult.Error); } var (customerId, address, amount) = combinedResult.Value; return Order.Create(customerId, address, amount); } ``` --- ## Domain Errors Pattern ```csharp // src/{name}.domain/Users/UserErrors.cs namespace {name}.domain.users; public static class UserErrors { public static readonly Error NotFound = new( "User.NotFound", "The user with the specified ID was not found"); public static readonly Error EmailAlreadyExists = new( "User.EmailExists", "A user with this email already exists"); public static readonly Error NameRequired = new( "User.NameRequired", "User name is required"); public static readonly Error NameTooLong = new( "User.NameTooLong", "User name cannot exceed 100 characters"); public static readonly Error InvalidCredentials = new( "User.InvalidCredentials", "The provided credentials are invalid"); public static readonly Error AccountLocked = new( "User.AccountLocked", "The user account is locked"); // Parameterized errors public static Error NotFoundById(Guid id) => new( "User.NotFound", $"The user with ID '{id}' was not found"); public static Error Unauthorized(string resource) => new( "User.Unauthorized", $"User is not authorized to access '{resource}'"); } ``` --- ## Critical Rules 1. **Never throw for business errors** - Return `Result.Failure` 2. **Always check IsSuccess/IsFailure** - Before accessing Value 3. **Use factory methods** - `Result.Success()`, `Result.Failure()` 4. **Errors are immutable** - `record Error(...)` 5. **Error codes are unique** - Follow `{Entity}.{ErrorType}` pattern 6. **Chain with Bind** - For sequential operations 7. **Use Match in controllers** - Clean response mapping 8. **Value objects validate in Create** - Return Result from factories 9. **Combine for multiple validations** - Returns first failure 10. **Keep Result in domain** - Don't leak to API layer directly --- ## Anti-Patterns to Avoid ```csharp // ❌ WRONG: Throwing for business errors if (user is null) throw new NotFoundException("User not found"); // ✅ CORRECT: Return Result if (user is null) return Result.Failure(UserErrors.NotFound); // ❌ WRONG: Accessing Value without checking var user = result.Value; // Throws if failed! // ✅ CORRECT: Check first if (result.IsFailure) return Result.Failure(result.Error); var user = result.Value; // ❌ WRONG: Ignoring Result await CreateUserAsync(request); // Ignores possible failure // ✅ CORRECT: Handle the result var result = await CreateUserAsync(request); if (result.IsFailure) // Handle error // ❌ WRONG: Using exceptions as control flow try { return Success(Process()); } catch (ValidationException ex) { return Failure(ex.Error); } // ✅ CORRECT: Design to return Result var validationResult = Validate(input); if (validationResult.IsFailure) return validationResult; return Success(Process(input)); ``` --- ## Related Skills - `dotnet-domain-entity-generator` - Use Result in factory methods - `dotnet-cqrs-command-generator` - Commands return Result - `dotnet-cqrs-query-generator` - Queries return Result - `dotnet-pipeline-behaviors` - Validation behavior uses Result