using MessageFlow; namespace MessageFlow.Samples; /// /// Contrasts a chain without a fallback (which throws ) /// with the same chain guarded by a fallback. /// public static class UnhandledRequestSample { /// /// Builds a chain that only understands positive numbers. /// /// /// When , unhandled requests produce a default response instead of throwing. /// /// The composed chain. public static IChain BuildChain(bool withFallback) { var builder = Chain.Create() .UseWhen(request => request > 0, (request, _) => new ValueTask($"handled:{request}")); if (withFallback) { builder = builder.WithFallback((_, _) => new ValueTask("unhandled, using default")); } return builder.Build(); } /// /// Executes a request and turns an into its message. /// /// The chain to execute. /// The request to send. /// A token used to cancel the operation. /// The response, or the message of the thrown exception. public static async Task DescribeAsync( IChain chain, int request, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(chain); try { return await chain.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } catch (UnhandledRequestException exception) { return exception.Message; } } /// /// Runs the sample, showing both the thrown exception and the fallback response. /// /// The writer receiving the sample output. /// A token used to cancel the operation. /// The descriptions produced for every chain and request combination. public static async Task> RunAsync( TextWriter output, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(output); var strict = BuildChain(withFallback: false); var lenient = BuildChain(withFallback: true); var results = new List(); foreach (var (name, chain, request) in new[] { ("strict", strict, 1), ("strict", strict, -1), ("lenient", lenient, -1), }) { var description = await DescribeAsync(chain, request, cancellationToken).ConfigureAwait(false); results.Add(description); await output.WriteLineAsync($"{name} {request} => {description}").ConfigureAwait(false); } return results; } }