Path: redb-route/redb.Route/Processors/TryCatchProcessor.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Processors/TryCatchProcessor.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Processors;
///
/// A catch clause used by .
/// Matches exceptions by type and executes a handler processor.
///
public class CatchClause
{
/// The exception type to catch.
public Type ExceptionType { get; }
/// Optional predicate for additional filtering.
public Func? When { get; }
/// Processor to execute when the exception is caught.
public IProcessor Handler { get; }
/// Creates a catch clause.
/// Exception type to match.
/// Handler processor.
/// Optional additional predicate.
public CatchClause(Type exceptionType, IProcessor handler, Func? when = null)
{
ExceptionType = exceptionType ?? throw new ArgumentNullException(nameof(exceptionType));
Handler = handler ?? throw new ArgumentNullException(nameof(handler));
if (!typeof(Exception).IsAssignableFrom(exceptionType))
throw new ArgumentException($"Type must be an Exception, got {exceptionType.Name}", nameof(exceptionType));
When = when;
}
/// Creates a typed catch clause.
/// Exception type to match.
/// Handler processor.
/// Optional additional predicate.
/// A new catch clause for the specified type.
public static CatchClause For(IProcessor handler, Func? when = null)
where TException : Exception
{
Func? wrappedWhen = when != null
? ex => ex is TException typed && when(typed)
: null;
return new CatchClause(typeof(TException), handler, wrappedWhen);
}
/// Checks whether this clause matches the given exception.
/// The exception to match.
/// True if this clause handles the exception.
public bool Matches(Exception exception)
{
if (!ExceptionType.IsInstanceOfType(exception))
return false;
return When == null || When(exception);
}
}
///
/// Try-catch error handling processor. Wraps a body processor and catches
/// exceptions using ordered catch clauses. Optionally runs a finally block.
///
public class TryCatchProcessor : IProcessor
{
private readonly IProcessor _body;
private readonly List _catchClauses = [];
private readonly ILogger? _logger;
private IProcessor? _finally;
/// Gets the catch clauses.
public IReadOnlyList CatchClauses => _catchClauses;
/// Gets the finally processor.
public IProcessor? Finally => _finally;
/// Creates a try-catch processor wrapping the specified body.
/// The processor to wrap in try-catch.
/// Optional logger.
public TryCatchProcessor(IProcessor body, ILogger? logger = null)
{
_body = body ?? throw new ArgumentNullException(nameof(body));
_logger = logger;
}
/// Adds a catch clause.
/// The catch clause to add.
/// This instance for fluent chaining.
public TryCatchProcessor Catch(CatchClause clause)
{
ArgumentNullException.ThrowIfNull(clause);
_catchClauses.Add(clause);
return this;
}
/// Adds a typed catch clause.
/// Exception type to catch.
/// Handler processor.
/// This instance for fluent chaining.
public TryCatchProcessor Catch(IProcessor handler) where TException : Exception
{
_catchClauses.Add(CatchClause.For(handler));
return this;
}
/// Sets the finally processor.
/// Processor to run after try/catch regardless of outcome.
/// This instance for fluent chaining.
public TryCatchProcessor SetFinally(IProcessor processor)
{
_finally = processor ?? throw new ArgumentNullException(nameof(processor));
return this;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
try
{
await _body.Process(exchange, ct).ConfigureAwait(false);
}
// A downstream timeout is an OperationCanceledException whose token (ours) is still live — not a
// cancellation, so it enters here. Name it a TimeoutException so Catch sees it;
// a genuine cancellation (the caller's token fired) is filtered out and never handled.
catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct))
{
var failure = RouteCancellation.Normalize(ex, ct);
exchange.Exception = failure;
var matched = false;
foreach (var clause in _catchClauses)
{
if (clause.Matches(failure))
{
_logger?.LogWarning(failure, "TryCatch: caught {ExceptionType}: {Message}",
failure.GetType().Name, failure.Message);
await clause.Handler.Process(exchange, ct).ConfigureAwait(false);
exchange.ExceptionHandled = true;
// The catch clause is where this failure ends; the steps left in the try body are deliberately
// abandoned, so nothing replays them later (OnException ... Continued()).
ResumePoints.Forget(exchange, failure);
matched = true;
break;
}
}
if (!matched)
throw;
}
finally
{
if (_finally != null)
{
await _finally.Process(exchange, ct).ConfigureAwait(false);
}
}
}
}