Repository navigation
Releases
Fluent.Unions 1.1.0
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
FromExceptionthat throws no longer loses the original exception. The operator now throws anInvalidOperationExceptionwhose innerAggregateExceptionholds both the original exception and the failure ofFromException. Before, only the mapping failure escaped. Analyzer FLU0009 already warns about such aFromException. - Malformed union JSON is rejected. A payload without
$value, or with a$valuethat would give an empty union, now throwsJsonException(System.Text.Json) orJsonSerializationException(Newtonsoft.Json) instead of reading as adefaultvalue. 1.0.0 never wrote such payloads. A case whose own converter readsnull, such asOption<T>, still reads it. - Clear errors for clashing case names. A union with two cases of the same name now throws an
InvalidOperationExceptionthat names both types and points to[UnionCaseName], instead of aTargetInvocationException.
Documentation
- The default result. One page now describes what a
defaultresult does in every library member and in native pattern matching: aswitchexpression throwsSwitchExpressionException, and aswitchstatement 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,ExceptionCaptureIErrorResult<TSelf, TError>.Captures(Exception), a static virtual member with a default implementationTap,TapError,TapAwait,MapError,Chain(step, combine),ChainAwait(step, combine), on every result type and onTaskof results where the operator family hasTaskoverloadsUnionCaseNameAttribute,UnionCaseNamesOptionJsonConverter<T>,UnionJsonConverter<TUnion>- Generator diagnostics FLU0104 (
Declaredcapture on anExceptionerror type has no effect) and FLU0105 (a type inPropagatethat is not an exception)
Fluent.Unions 1.0.0
Fluent.Unions 1.0.0 is the first production-ready release. The public API is now stable and follows semantic versioning from here on.
Result, Result<T> and Option<T> for .NET, built on the C# 15 union keyword. A method returns either its value or an error, and the compiler checks that callers handle both. Fluent operators are named after LINQ and Rx.NET, so a whole flow reads as one expression.
dotnet add package Fluent.Unions
Requires the .NET 11 SDK. Documentation: https://tobistr.github.io/Fluent.Unions/
Features
- Compiler-checked handling. A
switchover a result or option warns when a case is missing. Analyzers report ignored results, async lambdas that escape a result, unions that cannot tell their cases apart, serialized results and more, with code fixes. - Your own Result in one line.
[FluentResult<DomainException>] public readonly partial struct Result<T>;lets the source generator build a complete result around your error type: every operator, everyTaskoverload and the value-lessResult. Make the error a union and the compiler checks that every case is handled. - Built for hot paths. Results store their value without boxing, and a chain of operators with static lambdas allocates nothing.
- LINQ and Rx operators.
Select,Chain,Ensure,Zip,ChainAppend,Outon the value;Catch,Do,OnErrorDo,Finallyon the error;Match,TryGetValue,GetValueOrDefaultto leave the chain. Query syntax works too. Option<T>instead ofnull.TryParse,FirstOrNone,GetValueOrNone,Or, and conversions to and from results.- Async everywhere.
Taskoverloads,...Awaitoperators,Result.WhenAll,RetryAsync,Timeoutand async streams. Cancellation is never turned into an error. - Validation that collects every error.
Validate,CombineAlland a catalogue of ready-made rules such asEnsureNotEmptyandEnsureInRange, reported asValidationErrorswith property names. - More unions.
Loadable<T>for UI state, plusIs/Asand a JSON converter for your own unions. - Safe by default. Results refuse to serialize in every supported serializer, so exception details cannot leak.
ToString()of an error shows the type and message, never the stack trace.
Integrations
27 packages, one per library you already use:
| Area | Packages |
|---|---|
| Web | Fluent.Unions.AspNetCore (ProblemDetails, ValidationProblemDetails, endpoint filter), Fluent.Unions.OpenApi, Fluent.Unions.Swashbuckle, Fluent.Unions.NSwag, Fluent.Unions.HotChocolate, Fluent.Unions.Grpc, Fluent.Unions.Refit |
| Application | Fluent.Unions.FluentValidation, Fluent.Unions.Polly, Fluent.Unions.Mediator, Fluent.Unions.MediatR, Fluent.Unions.Serilog |
| Data and serialization | Fluent.Unions.NewtonsoftJson, Fluent.Unions.MessagePack, Fluent.Unions.Orleans, Fluent.Unions.MongoDB, Fluent.Unions.Dapper, Fluent.Unions.Mapster, Fluent.Unions.AutoMapper |
| Testing | Fluent.Unions.AwesomeAssertions, Fluent.Unions.FluentAssertions, Fluent.Unions.Shouldly, Fluent.Unions.TUnit, Fluent.Unions.NUnit, Fluent.Unions.Xunit, Fluent.Unions.Verify |
System.Text.Json support and OpenTelemetry (Activity.RecordResult) are part of the core package. Every integration works with your own declared result types as well as the built-in ones.
What changed since 0.3.0
1.0.0 consolidates the API after a full review for usability, security, performance and robustness.
Breaking changes
Result<T, TError>and hand-written result types that implementIResult<TSelf, T, TError>are removed. Declare the type with[FluentResult<TError>]instead; see Migrating from 0.3.0.SelectManyAwaitis removed; useChainAwait.BindAppendandBindAppendAwaitare renamed toChainAppendandChainAppendAwait.- The
Companionoption of[FluentResult]is removed. The value-less companion is generated unless you declare your own[FluentResult]struct with the same name. - Generated operator classes are named
{Type}{Group}Operators, for exampleResultOperatorsandResultTaskOperators, so they no longer collide with your ownResultExtensions. IsSuccessandTryGetErrormoved toIErrorResult<TSelf, TError>, and a non-genericIErrorResultreads any result without reflection.ErrorResultExtensionsis removed.- Registration is named consistently:
WithFluentUnions()for MessagePack,AddFluentUnions()for Orleans,FluentUnionsDapper.Register()for Dapper. Every registration is safe to call twice. - gRPC:
ResultGrpcOptionsis configured withservices.Configure<ResultGrpcOptions>(...). AnRpcExceptioncaptured from a downstream call keeps only its status code; the original is inStatus.DebugException. - ASP.NET Core: a faulted
Task<Result<T>>propagates to the framework's exception handling instead of becoming a 500.ResultHttpOptions.GetStatusCodeis removed. default(Option<T>)now equalsOption.None, anddefault(Loadable<T>)equalsNotLoaded.
Security
UnionJsonConverter(System.Text.Json and Newtonsoft.Json) no longer serializes results or options when it is registered globally.ToString()of an error result no longer includes the stack trace.- HotChocolate raises non-exception errors as field errors instead of exposing them as values.
- The documented domain error setup no longer sends internal exception messages to HTTP clients.
Robustness and performance
- The source generator reports clear diagnostics (FLU0101 to FLU0103, with help links) instead of compiler errors in generated code, handles keyword identifiers and costs almost nothing in projects without
[FluentResult]. - Analyzer fixes: no false FLU0001 on
OnErrorDoandDofor declared types, and the FLU0012 code fix only appears when the result compiles. RetryAsyncretries timeouts that are not caller cancellation. Async-stream helpers, assertion packages, NUnit, Serilog and Verify decide Ok and Error by the result's state.- ASP.NET Core logs 5xx responses, treats empty results consistently and maps wrapped validation errors to ValidationProblemDetails.
- Dapper maps enums stored as text and
DateTimecolumns toDateTimeOffset. Verify keeps the labels of nested unions. HotChocolate unwrapsResult<Option<T>>to a nullable field. - Result type detection and regular expressions are cached.
Full Changelog: v0.3.0...v1.0.0