Path: redb-route/redb.Route/Definitions/OnExceptionDefinition.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/Definitions/OnExceptionDefinition.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Predicates;
using redb.Route.Processors;
namespace redb.Route.Definitions;
///
/// Scope-opener definition for route-level exception handling.
/// Wraps the child pipeline with an that
/// retries, handles, or continues on the configured exception types.
/// Configure redelivery settings with ,
/// , etc., then close with or
/// . Inherits the leaf DSL from ;
/// child steps build the handler body.
///
public class OnExceptionDefinition : RouteDefinitionBase, IRouteScope
{
private readonly List _exceptionTypes;
private int _maxRedeliveries;
private TimeSpan? _redeliveryDelay;
private double _backoffMultiplier = 1.0;
private bool _useExponentialBackoff;
private bool _handled;
private bool _continued;
// ── Public properties for test/inspection ─────────────────────────────────
/// Exception types this handler applies to.
public IReadOnlyList ExceptionTypes => _exceptionTypes;
/// Maximum number of redelivery (retry) attempts.
public int MaxRedeliveries => _maxRedeliveries;
/// Delay between retry attempts (null = default 1 second). Inspection accessor.
public TimeSpan? RedeliveryDelayValue => _redeliveryDelay;
/// Backoff multiplier applied to the delay after each retry.
public double BackoffMultiplierValue => _backoffMultiplier;
/// Whether exponential backoff is enabled.
public bool UseExponentialBackoffValue => _useExponentialBackoff;
/// Whether the exception is marked as handled (suppresses propagation).
public bool IsHandled => _handled;
/// Whether exchange processing continues after the handler runs.
public bool IsContinued => _continued;
internal OnExceptionDefinition(IEnumerable exceptionTypes)
{
_exceptionTypes = [.. exceptionTypes];
}
// ── Configuration ─────────────────────────────────────────────────────────
/// Applies all settings from a pre-built .
public OnExceptionDefinition RedeliveryPolicy(RedeliveryPolicy policy)
{
ArgumentNullException.ThrowIfNull(policy);
_maxRedeliveries = policy.MaximumRedeliveries;
_redeliveryDelay = policy.RedeliveryDelay;
_backoffMultiplier = policy.BackOffMultiplier;
_useExponentialBackoff = policy.UseExponentialBackOff;
return this;
}
/// Sets the maximum number of redelivery attempts.
public OnExceptionDefinition MaximumRedeliveries(int count)
{
_maxRedeliveries = count;
return this;
}
/// Marks the exception as handled (suppresses further propagation).
public OnExceptionDefinition Handled(bool value = true)
{
_handled = value;
return this;
}
///
/// Suppresses the failure and picks the route up at the step after the one that failed (Apache Camel's
/// continued(true)), where ends the route where it failed. A step inside a scope
/// resumes that scope first and then the steps after it; work a transaction rolled back is not replayed, and routing
/// picks up after the block. A failure among the resumed steps is matched against the handlers anew, but not
/// redelivered: a redelivery re-runs the route from its first step.
///
public OnExceptionDefinition Continued(bool value = true)
{
_continued = value;
return this;
}
/// Sets the delay between retry attempts.
public OnExceptionDefinition RedeliveryDelay(TimeSpan delay)
{
_redeliveryDelay = delay;
return this;
}
/// Sets the backoff multiplier applied to the delay after each retry.
public OnExceptionDefinition BackOffMultiplier(double multiplier)
{
_backoffMultiplier = multiplier;
return this;
}
/// Enables (or disables) exponential backoff between retries.
public OnExceptionDefinition UseExponentialBackOff(bool value = true)
{
_useExponentialBackoff = value;
return this;
}
/// Apache Camel alias for .
public OnExceptionDefinition BackoffMultiplier(double multiplier) => BackOffMultiplier(multiplier);
/// Apache Camel alias for .
public OnExceptionDefinition UseExponentialBackoff(bool value = true) => UseExponentialBackOff(value);
/// Marks that the original (pre-exception) body should be restored for the handler.
public OnExceptionDefinition UseOriginalBody()
{
_useOriginalBody = true;
return this;
}
private bool _useOriginalBody;
/// Whether the original body restoration is enabled.
public bool IsUseOriginalBody => _useOriginalBody;
/// Conditional predicate — only handle when predicate returns true.
public OnExceptionDefinition OnWhen(Func predicate)
{
_onWhen = predicate ?? throw new ArgumentNullException(nameof(predicate));
return this;
}
///
/// Conditional predicate written as a route expression, the spelling a declarative route
/// needs (${header.retryable} == 'true') — the string form
/// already takes.
///
public OnExceptionDefinition OnWhen(string condition)
{
ArgumentException.ThrowIfNullOrWhiteSpace(condition);
var predicate = PredicateFactory.FromString(condition);
return OnWhen(predicate.Matches);
}
/// Conditional predicate as an (Header("retryable").isEqualTo("true")).
public OnExceptionDefinition OnWhen(IPredicate predicate)
=> OnWhen((predicate ?? throw new ArgumentNullException(nameof(predicate))).Matches);
private Func? _onWhen;
/// Optional predicate gating handler activation.
public Func? OnWhenPredicate => _onWhen;
/// Retry while the predicate returns true.
public OnExceptionDefinition RetryWhile(Func predicate)
{
_retryWhile = predicate ?? throw new ArgumentNullException(nameof(predicate));
return this;
}
/// Retry while the route expression holds — the string form of .
public OnExceptionDefinition RetryWhile(string condition)
{
ArgumentException.ThrowIfNullOrWhiteSpace(condition);
var predicate = PredicateFactory.FromString(condition);
return RetryWhile(predicate.Matches);
}
/// Retry while the holds.
public OnExceptionDefinition RetryWhile(IPredicate predicate)
=> RetryWhile((predicate ?? throw new ArgumentNullException(nameof(predicate))).Matches);
private Func? _retryWhile;
/// Optional predicate controlling retry continuation.
public Func? RetryWhilePredicate => _retryWhile;
/// Callback invoked when the handler itself fails.
public OnExceptionDefinition OnPrepareFailure(Action action)
{
_onPrepareFailure = action ?? throw new ArgumentNullException(nameof(action));
return this;
}
private Action? _onPrepareFailure;
/// Optional pre-failure callback.
public Action? OnPrepareFailureAction => _onPrepareFailure;
///
/// Processor invoked before the handler runs, once the redeliveries are exhausted (Apache Camel's
/// onPrepareFailure, which takes a Processor too). The markup form of a route can only name a processor —
/// a bean from the registry — so the callbacks take one beside the delegate.
///
public OnExceptionDefinition OnPrepareFailure(IProcessor processor)
{
_onPrepareFailureProcessor = processor ?? throw new ArgumentNullException(nameof(processor));
return this;
}
private IProcessor? _onPrepareFailureProcessor;
/// Optional pre-failure processor.
public IProcessor? OnPrepareFailureProcessor => _onPrepareFailureProcessor;
/// Callback invoked on each redelivery attempt.
public OnExceptionDefinition OnRedelivery(Action action)
{
_onRedelivery = action ?? throw new ArgumentNullException(nameof(action));
return this;
}
private Action? _onRedelivery;
/// Optional redelivery callback.
public Action? OnRedeliveryAction => _onRedelivery;
/// Processor invoked before each redelivery attempt (Apache Camel's onRedelivery).
public OnExceptionDefinition OnRedelivery(IProcessor processor)
{
_onRedeliveryProcessor = processor ?? throw new ArgumentNullException(nameof(processor));
return this;
}
private IProcessor? _onRedeliveryProcessor;
/// Optional redelivery processor.
public IProcessor? OnRedeliveryProcessor => _onRedeliveryProcessor;
/// Callback invoked when the exception occurs (before any retry).
public OnExceptionDefinition OnExceptionOccurred(Action action)
{
_onExceptionOccurred = action ?? throw new ArgumentNullException(nameof(action));
return this;
}
private Action? _onExceptionOccurred;
/// Optional exception-occurred callback.
public Action? OnExceptionOccurredAction => _onExceptionOccurred;
///
/// Processor invoked every time the exception occurs, before any retry (Apache Camel's onExceptionOccurred).
///
public OnExceptionDefinition OnExceptionOccurred(IProcessor processor)
{
_onExceptionOccurredProcessor = processor ?? throw new ArgumentNullException(nameof(processor));
return this;
}
private IProcessor? _onExceptionOccurredProcessor;
/// Optional exception-occurred processor.
public IProcessor? OnExceptionOccurredProcessor => _onExceptionOccurredProcessor;
/// Log level used for retry-attempt log entries.
public OnExceptionDefinition RetryAttemptedLogLevel(LogLevel level)
{
_retryAttemptedLogLevel = level;
return this;
}
private LogLevel _retryAttemptedLogLevel = LogLevel.Debug;
/// Log level for retry-attempt log entries (default Debug).
public LogLevel RetryAttemptedLogLevelValue => _retryAttemptedLogLevel;
/// Log level used when retries are exhausted.
public OnExceptionDefinition RetriesExhaustedLogLevel(LogLevel level)
{
_retriesExhaustedLogLevel = level;
return this;
}
private LogLevel _retriesExhaustedLogLevel = LogLevel.Error;
/// Log level used when retries are exhausted (default Error).
public LogLevel RetriesExhaustedLogLevelValue => _retriesExhaustedLogLevel;
/// Whether to include the full stack trace in retry log messages (default: true).
public OnExceptionDefinition LogStackTrace(bool value = true)
{
_logStackTrace = value;
return this;
}
private bool _logStackTrace = true;
/// Current LogStackTrace value (default true).
public bool LogStackTraceValue => _logStackTrace;
/// Whether to emit a log entry when retries are exhausted (default: true).
public OnExceptionDefinition LogExhausted(bool value = true)
{
_logExhausted = value;
return this;
}
private bool _logExhausted = true;
/// Current LogExhausted value (default true).
public bool LogExhaustedValue => _logExhausted;
/// Whether the exhausted-failure log entry is written for a failure the handler handled (default: false, as in Camel).
public OnExceptionDefinition LogHandled(bool value = true)
{
_logHandled = value;
return this;
}
private bool _logHandled;
/// Current LogHandled value (default false).
public bool LogHandledValue => _logHandled;
/// Whether the exhausted-failure log entry is written for a failure the handler continued (default: false, as in Camel).
public OnExceptionDefinition LogContinued(bool value = true)
{
_logContinued = value;
return this;
}
private bool _logContinued;
/// Current LogContinued value (default false).
public bool LogContinuedValue => _logContinued;
// ── Navigation ─────────────────────────────────────────────────────────────
/// Closes this OnException scope and returns the parent route definition.
public IRouteDefinition EndOnException()
=> (IRouteDefinition)(Parent ?? throw new InvalidOperationException(
"EndOnException() called without a parent route."));
///
public IRouteDefinition End() => EndOnException();
// ── IProcessorDefinition ──────────────────────────────────────────────────
///
/// Whether this definition was hoisted by
/// to wrap the route body (Camel parity: OnException is route-scoped regardless of
/// where it is declared, including inside nested scopes).
///
internal bool IsHoisted { get; private set; }
/// Marks this definition as hoisted by the route compiler.
internal void MarkHoisted() => IsHoisted = true;
///
///
/// OnException is compiled exclusively through the hoisting pass in
/// , which calls .
/// When hoisted, the declaration site compiles to a pass-through no-op.
/// When NOT hoisted (e.g., declared inside a Catch/Finally block or another
/// OnException handler pipeline — placements that the route compiler does not
/// hoist), this throws instead of silently emitting the handler chain as an
/// inline pipeline step, which would corrupt every passing exchange.
///
public override IProcessor CreateProcessor(IRouteContext context)
{
if (IsHoisted)
return new DelegateProcessor(_ => { });
throw new InvalidOperationException(
"OnException is route-scoped and is compiled via RouteDefinition hoisting. " +
"This OnException block was declared at a location the route compiler cannot hoist " +
"(e.g., inside a Catch/Finally block or another exception handler pipeline). " +
"Declare OnException in the route body (any scope) or at the RouteBuilder level.");
}
///
/// Wraps the supplied processor with one for all of
/// , each with its own pipeline of child .
/// Used for a route compiled outside a ; the route compiler of a context goes through
/// the route's , which compiles a handler once and reuses it.
///
internal static IProcessor WrapBody(IProcessor body, IReadOnlyList handlers, IRouteContext context)
{
ArgumentNullException.ThrowIfNull(body);
ArgumentNullException.ThrowIfNull(context);
var logger = context.GetService()?.CreateLogger();
var scope = new OnExceptionProcessor(body, logger);
foreach (var handler in handlers)
handler.AddTo(scope, TryCatchDefinition.BuildPipeline(handler.Outputs, context));
return scope;
}
///
/// The one place an is configured from this definition. Registers it in
/// , the processor of a whole scope: every exception type with
/// (this definition's compiled steps) and every setting of the definition.
///
internal void AddTo(OnExceptionProcessor oeProc, IProcessor handlerBody)
{
ArgumentNullException.ThrowIfNull(oeProc);
ArgumentNullException.ThrowIfNull(handlerBody);
foreach (var type in _exceptionTypes)
{
oeProc.Handle(type, handlerBody,
maxRedeliveries: _maxRedeliveries,
redeliveryDelay: _redeliveryDelay,
backoffMultiplier: _backoffMultiplier,
useExponentialBackoff: _useExponentialBackoff,
handled: _handled,
continued: _continued,
onWhenPredicate: _onWhen,
retryAttemptedLogLevel: _retryAttemptedLogLevel,
retriesExhaustedLogLevel: _retriesExhaustedLogLevel,
onExceptionOccurred: _onExceptionOccurred,
retryWhile: _retryWhile,
onRedelivery: _onRedelivery,
onPrepareFailure: _onPrepareFailure,
useOriginalBody: _useOriginalBody,
logStackTrace: _logStackTrace,
logExhausted: _logExhausted,
logHandled: _logHandled,
logContinued: _logContinued,
onExceptionOccurredProcessor: _onExceptionOccurredProcessor,
onRedeliveryProcessor: _onRedeliveryProcessor,
onPrepareFailureProcessor: _onPrepareFailureProcessor);
}
}
}