Skip to content

Fluent.Unions 1.1.0

Latest

Choose a tag to compare

@github-actions github-actions released this 22 Nov 12:05
· 7 commits to main since this release

Fluent.Unions 1.1.0 hardens the library after a review of its riskiest behaviour: how exceptions are captured, what happens when a side effect fails, how default results behave, how JSON payloads survive refactoring, and whether the library works in native AOT apps. Every change is additive. Code written for 1.0.0 compiles and behaves as before, apart from the three narrow fixes listed under Behaviour fixes.

dotnet add package Fluent.Unions --version 1.1.0

Documentation: https://tobistr.github.io/Fluent.Unions/

Highlights

Choose which exceptions become errors

By default every exception thrown inside an operator becomes an error. That keeps a chain from throwing, but a bug such as a NullReferenceException then looks like an ordinary business failure. Your own result type can now narrow that:

// Only DomainException and its subtypes become errors; everything else escapes.
[FluentResult<DomainException>(Capture = ExceptionCapture.Declared)]
public readonly partial struct Result<T>;

// Capture everything except these.
[FluentResult<DomainException>(Propagate = [typeof(NullReferenceException), typeof(ArgumentException)])]
public readonly partial struct Result<T>;

An excluded exception is never caught, so it keeps its original stack trace and the debugger stops where it was thrown. The policy applies to every operator, to Try and Retry, and to the MediatR, Mediator, Polly and FluentValidation integrations. With Declared, an error union whose cases are exceptions captures exactly those cases. The default Result<T> is unchanged and still captures everything except OperationCanceledException. See Capture policy.

Observers that cannot overwrite the outcome

Do treats its callback as part of the chain: if a logger throws after an order was saved, the saved order becomes an error. The new Tap, TapError and TapAwait never capture. An observer failure propagates as itself, and TapError keeps the original error:

Result<Order> placed = PlaceOrder(cart)
    .Tap(order => metrics.OrderPlaced(order.Total))
    .TapError(error => logger.LogWarning(error, "Order failed"));

Use Do for side effects that must succeed, and Tap for logging and metrics. See Do or Tap.

Translate errors between layers with MapError

Every result type, including the built-in Result<T> and Result, now has MapError, which moves a result to the result type of another layer. It keeps the value and maps the error, and the target type is named once:

ClientResult<Order> ForClient(Outcome<Order> outcome) =>
    outcome.MapError<ClientResult<Order>, ClientError>(error => error switch
    {
        CustomerNotFound missing => new BadRequest($"No customer {missing.Id}."),
        PaymentDeclined declined => new BadRequest(declined.Reason),
        Unexpected => new ServerError()
    });

The switch is target-typed, so its arms need no cast, and a new error case still fails the build. See Translating errors between layers.

Lazy combination with Chain(step, combine)

Zip takes results that already exist, so its argument runs even when the first result failed. Chain(step, combine) and ChainAwait(step, combine) run the second step only after the first succeeded, and then combine both values:

Result<Order> order = FindCustomer(id).Chain(
    customer => FindProduct(sku),
    (customer, product) => new Order(customer, product));

The docs now state which operators evaluate their arguments eagerly, and the README example no longer runs a lookup after a failed step.

Stable JSON case names for your own unions

UnionJsonConverter names a case after its type, so renaming the type broke stored payloads, and List<int> next to List<string> could not be told apart. [UnionCaseName] gives a case a name that does not depend on its type, and aliases keep old names readable:

[JsonConverter(typeof(UnionJsonConverter))]
[UnionCaseName(typeof(Circle), "circle", Aliases = ["Circle"])]
[UnionCaseName(typeof(List<int>), "numbers")]
[UnionCaseName(typeof(List<string>), "words")]
public union Drawing(Circle, List<int>, List<string>);

The System.Text.Json and Newtonsoft.Json converters both read the attribute. Cases without it keep their type name, and golden tests pin the 1.0.0 wire format, so existing payloads keep reading and writing byte for byte. See Stable case names.

Tested native AOT and trimming support

The core package is now marked AOT-compatible. CI publishes a sample app as native AOT and as a trimmed app on every push, runs it, and fails on any trim or AOT warning. The sample covers results, options, declared result types, the capture policy, MapError, Tap and System.Text.Json. For AOT apps there are two new converters that need no runtime code generation:

[JsonSourceGenerationOptions(Converters = [typeof(OptionJsonConverter<int>)])]
[JsonSerializable(typeof(CustomerDto))]
[JsonSerializable(typeof(int))]
public partial class AppJsonContext : JsonSerializerContext;

[JsonConverter(typeof(UnionJsonConverter<Shape>))]
public union Shape(Circle, Square);

Where something cannot work under AOT, it now fails with a message that names the fix. The Newtonsoft.Json, MessagePack and MongoDB registrations, which rely on reflection, carry RequiresUnreferencedCode and RequiresDynamicCode. See the compatibility matrix.

Behaviour fixes

  • A FromException that throws no longer loses the original exception. The operator now throws an InvalidOperationException whose inner AggregateException holds both the original exception and the failure of FromException. Before, only the mapping failure escaped. Analyzer FLU0009 already warns about such a FromException.
  • Malformed union JSON is rejected. A payload without $value, or with a $value that would give an empty union, now throws JsonException (System.Text.Json) or JsonSerializationException (Newtonsoft.Json) instead of reading as a default value. 1.0.0 never wrote such payloads. A case whose own converter reads null, such as Option<T>, still reads it.
  • Clear errors for clashing case names. A union with two cases of the same name now throws an InvalidOperationException that names both types and points to [UnionCaseName], instead of a TargetInvocationException.

Documentation

  • The default result. One page now describes what a default result does in every library member and in native pattern matching: a switch expression throws SwitchExpressionException, and a switch statement runs no branch. Every case is covered by tests.
  • What is captured. Error handling now lists which exceptions operators capture, the order of precedence when a callback throws, and that a chain is not a transaction.
  • FLU0007. The analyzer docs explain what FLU0007 cannot see and how to make it an error.
  • Nested options. Option<Option<T>> is documented as not a round-trip type for JSON, MessagePack and MongoDB; Orleans keeps both levels.

New API

  • FluentResultAttribute<TError>.Capture, FluentResultAttribute<TError>.Propagate, ExceptionCapture
  • IErrorResult<TSelf, TError>.Captures(Exception), a static virtual member with a default implementation
  • Tap, TapError, TapAwait, MapError, Chain(step, combine), ChainAwait(step, combine), on every result type and on Task of results where the operator family has Task overloads
  • UnionCaseNameAttribute, UnionCaseNames
  • OptionJsonConverter<T>, UnionJsonConverter<TUnion>
  • Generator diagnostics FLU0104 (Declared capture on an Exception error type has no effect) and FLU0105 (a type in Propagate that is not an exception)