Path: redb-route/redb.Route/Processors/OnExceptionProcessor.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/OnExceptionProcessor.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.ErrorHandling; namespace redb.Route.Processors; /// /// The OnException handlers of one scope around a body: handles the failures a per-step /// TryCatchProcessor did not, with redelivery (delay, exponential backoff, max attempts). /// /// The handler is chosen as Apache Camel's DefaultExceptionPolicyStrategy chooses it: the failure is walked /// from its innermost cause up to the exception that was thrown; a handler of exactly that type wins at once; /// otherwise the handler whose type is the nearest ancestor does, the earlier exception of the walk and the earlier /// declared handler winning a tie. The smallest distance over the whole chain wins, as in Camel's source: a cause /// whose nearest handler is further away loses to the thrown exception's nearer one, even a catch-all. A handler /// whose OnWhen is false is passed over. A later handler of the same /// type without OnWhen replaces the earlier one. /// /// /// A route has two such scopes, the route's own handlers inside and the ones shared with other routes (its route /// configurations and its builder) outside. The inner one leaves a failure to the outer one when that has a strictly /// nearer handler; on a tie the route's own handler wins. /// /// public class OnExceptionProcessor : IProcessor { private readonly IProcessor _body; private readonly List _handlers = []; private readonly ILogger? _logger; /// /// The scope around this one. A failure this scope could take is left to it when it has a strictly nearer handler. /// internal OnExceptionProcessor? Outer { get; set; } /// Creates an on-exception processor wrapping the body. /// The main processor pipeline to protect. /// Optional logger for exception diagnostics. public OnExceptionProcessor(IProcessor body, ILogger? logger = null) { _body = body ?? throw new ArgumentNullException(nameof(body)); _logger = logger; } /// Registers a handler for a specific exception type. /// Exception type to handle. /// Handler processor. /// Maximum retry attempts before giving up (default: 0, no retry). /// Delay between retry attempts (default: 1 second). /// Backoff multiplier (default: 1.0 = fixed delay). /// Whether to apply exponential backoff (default: false). /// Whether the exception is marked as handled (default: false). /// Whether to continue the pipeline after the handler runs (default: false). /// Optional guard predicate. /// Log level for retry attempt messages (default: Warning). /// Log level when retries are exhausted (default: Error). /// Optional callback on each exception occurrence. /// Optional predicate — retry continues while true. /// Optional callback before each redelivery. /// Optional callback before handler/DLQ after retries exhausted. /// Restore original message before retries and handler. /// Restore original body only before retries and handler. /// Allow retries during cancellation. /// Include stack trace in retry logs. /// Log when retries are exhausted. /// Log the exhausted failure when the handler handled it (default: false, as in Camel). /// Log the exhausted failure when the handler continued it (default: false, as in Camel). /// This instance for fluent chaining. public OnExceptionProcessor Handle( IProcessor handler, int maxRedeliveries = 0, TimeSpan? redeliveryDelay = null, double backoffMultiplier = 1.0, bool useExponentialBackoff = false, bool handled = false, bool continued = false, Func? onWhenPredicate = null, LogLevel retryAttemptedLogLevel = LogLevel.Warning, LogLevel retriesExhaustedLogLevel = LogLevel.Error, Action? onExceptionOccurred = null, Func? retryWhile = null, Action? onRedelivery = null, Action? onPrepareFailure = null, bool useOriginalMessage = false, bool useOriginalBody = false, bool allowRedeliveryWhileStopping = false, bool logStackTrace = true, bool logExhausted = true, bool logHandled = false, bool logContinued = false) where TException : Exception { return Handle(typeof(TException), handler, maxRedeliveries, redeliveryDelay, backoffMultiplier, useExponentialBackoff, handled, continued, onWhenPredicate, retryAttemptedLogLevel, retriesExhaustedLogLevel, onExceptionOccurred, retryWhile, onRedelivery, onPrepareFailure, useOriginalMessage, useOriginalBody, allowRedeliveryWhileStopping, logStackTrace, logExhausted, logHandled: logHandled, logContinued: logContinued); } /// Registers a handler for a specific exception type (non-generic). public OnExceptionProcessor Handle( Type exceptionType, IProcessor handler, int maxRedeliveries = 0, TimeSpan? redeliveryDelay = null, double backoffMultiplier = 1.0, bool useExponentialBackoff = false, bool handled = false, bool continued = false, Func? onWhenPredicate = null, LogLevel retryAttemptedLogLevel = LogLevel.Warning, LogLevel retriesExhaustedLogLevel = LogLevel.Error, Action? onExceptionOccurred = null, Func? retryWhile = null, Action? onRedelivery = null, Action? onPrepareFailure = null, bool useOriginalMessage = false, bool useOriginalBody = false, bool allowRedeliveryWhileStopping = false, bool logStackTrace = true, bool logExhausted = true, // The processor forms of the three callbacks: the markup can only name a bean, and a bean is an IProcessor. // New parameters go last and optional, and land on init-only properties of the handler record: a new positional // parameter would shift the ones after it and break every caller built against the old order. IProcessor? onExceptionOccurredProcessor = null, IProcessor? onRedeliveryProcessor = null, IProcessor? onPrepareFailureProcessor = null, // Camel's LogHandled / LogContinued: whether the exhausted-failure log entry is written when the handler handled // (or continued) the failure. Both false by default, as in Camel. A rollback-only exchange bypasses both checks. bool logHandled = false, bool logContinued = false) { ArgumentNullException.ThrowIfNull(exceptionType); ArgumentNullException.ThrowIfNull(handler); RetryPolicy? retryPolicy = null; if (maxRedeliveries > 0) { var delay = redeliveryDelay ?? TimeSpan.FromSeconds(1); var multiplier = useExponentialBackoff ? Math.Max(backoffMultiplier, 2.0) : backoffMultiplier; retryPolicy = new RetryPolicy { MaxRetries = maxRedeliveries, InitialDelay = delay, BackoffMultiplier = multiplier, MaxDelay = TimeSpan.FromMinutes(5) }; } var registered = new ExceptionHandler(exceptionType, handler, maxRedeliveries, retryPolicy, handled, continued, onWhenPredicate, retryAttemptedLogLevel, retriesExhaustedLogLevel, onExceptionOccurred, retryWhile, onRedelivery, onPrepareFailure, useOriginalMessage, useOriginalBody, allowRedeliveryWhileStopping, logStackTrace, logExhausted, logHandled, logContinued) { OnExceptionOccurredProcessor = onExceptionOccurredProcessor, OnRedeliveryProcessor = onRedeliveryProcessor, OnPrepareFailureProcessor = onPrepareFailureProcessor, }; // Camel keys its policies by exception type and OnWhen: a later handler of the same type without OnWhen takes // the place of the earlier one (so a route configuration's handler is used instead of the builder's). Handlers // with an OnWhen are each their own entry. var same = onWhenPredicate is null ? _handlers.FindIndex(h => h.ExceptionType == exceptionType && h.OnWhenPredicate is null) : -1; if (same >= 0) _handlers[same] = registered; else _handlers.Add(registered); return this; } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { // Snapshot original message/body BEFORE processing (any handler may need it) object? originalBody = null; IDictionary? originalHeaders = null; var needsSnapshot = _handlers.Any(h => h.UseOriginalMessage || h.UseOriginalBody); if (needsSnapshot) { originalBody = exchange.In.Body; if (_handlers.Any(h => h.UseOriginalMessage)) originalHeaders = new Dictionary(exchange.In.Headers); } var attempt = 0; // Set by a Continued handler: the next turn replays the steps after the one that failed instead of the body. Exception? continueAfter = null; while (true) { var resuming = continueAfter is not null; try { if (continueAfter is { } failure) { continueAfter = null; await ResumePoints.ResumeAsync(exchange, failure, ct).ConfigureAwait(false); } else { await _body.Process(exchange, ct).ConfigureAwait(false); } return; // Success — exit } // A downstream timeout is an OperationCanceledException whose token (ours) is still live — not a // cancellation, so it enters here and is named a TimeoutException so OnException // matches it. A genuine cancellation (the caller's token fired) is filtered out, never swallowed. catch (Exception ex) when (!RouteCancellation.IsCancellation(ex, ct)) { ex = RouteCancellation.Normalize(ex, ct); exchange.Exception = ex; var (handler, distance) = FindHandler(ex, exchange); if (handler == null) throw; // No handler — rethrow // The scope around has a strictly nearer handler: the failure is its to take. if (Outer?.FindHandler(ex, exchange) is { Handler: not null } outer && outer.Distance < distance) throw; // Invoke callback if registered handler.OnExceptionOccurred?.Invoke(exchange); if (handler.OnExceptionOccurredProcessor is { } occurred) await occurred.Process(exchange, ct).ConfigureAwait(false); // B10: Set redelivery headers exchange.In.Headers["CamelRedelivered"] = attempt > 0; exchange.In.Headers["CamelRedeliveryCounter"] = attempt; // Check if we should continue retrying. A failure in steps replayed after a continue is not retried: // a redelivery re-runs the route from its first step, which would repeat what already succeeded. var shouldRetry = false; if (resuming) { shouldRetry = false; } else if (handler.RetryWhile != null) { // RetryWhile takes priority — retry as long as predicate returns true shouldRetry = handler.RetryWhile(exchange); } else { shouldRetry = attempt < handler.MaxRedeliveries; } // B7: Check if redelivery is allowed while stopping if (shouldRetry && !handler.AllowRedeliveryWhileStopping && ct.IsCancellationRequested) shouldRetry = false; if (shouldRetry) { attempt++; exchange.In.Headers["CamelRedeliveryCounter"] = attempt; exchange.In.Headers["CamelRedelivered"] = true; if (handler.LogStackTrace) { _logger?.Log(handler.RetryAttemptedLogLevel, ex, "Redelivery attempt {Attempt}/{Max} for {ExceptionType}", attempt, handler.MaxRedeliveries, ex.GetType().Name); } else { _logger?.Log(handler.RetryAttemptedLogLevel, "Redelivery attempt {Attempt}/{Max} for {ExceptionType}: {Message}", attempt, handler.MaxRedeliveries, ex.GetType().Name, EndpointUri.RedactSecrets(ex.Message)); } // Apply redelivery delay if (handler.RetryPolicy != null) { var delay = handler.RetryPolicy.GetDelay(attempt - 1); if (delay > TimeSpan.Zero) await InflightWaits.DelayAsync(exchange, delay, ct).ConfigureAwait(false); } // B6: Restore original message/body before retry RestoreOriginal(exchange, handler, originalBody, originalHeaders); // B4: OnRedelivery callback before each retry handler.OnRedelivery?.Invoke(exchange); if (handler.OnRedeliveryProcessor is { } redelivery) await redelivery.Process(exchange, ct).ConfigureAwait(false); exchange.Exception = null; exchange.ExceptionHandled = false; exchange.ClearFailureHandled(); // a redelivery is not a handled failure yet continue; // Retry } // Retries exhausted — B10: set exhausted flag exchange.In.Headers["CamelRedeliveryExhausted"] = true; exchange.In.Headers["CamelRedeliveryMaxCounter"] = handler.MaxRedeliveries; // B8: Log exhausted. Camel's RedeliveryErrorHandler.logFailedDelivery logs a handled failure only when // LogHandled, a continued one only when LogContinued. Both checks are bypassed for a rollback-only // exchange: its work was rolled back, so the failure is real even if the handler answered a client. var logThisFailure = handler.LogExhausted && (exchange.IsRollbackOnly() || !((handler.Handled && !handler.LogHandled) || (handler.Continued && !handler.LogContinued))); if (logThisFailure) { if (handler.LogStackTrace) { _logger?.Log(handler.RetriesExhaustedLogLevel, ex, "Retries exhausted for {ExceptionType} after {Attempts} attempts", ex.GetType().Name, attempt); } else { _logger?.Log(handler.RetriesExhaustedLogLevel, "Retries exhausted for {ExceptionType} after {Attempts} attempts: {Message}", ex.GetType().Name, attempt, EndpointUri.RedactSecrets(ex.Message)); } // Dump the message-history trail (when recorded) so the failing step is visible. var history = Core.MessageHistory.Format(exchange); if (!string.IsNullOrEmpty(history)) _logger?.Log(handler.RetriesExhaustedLogLevel, "{MessageHistory}", history); } // B6: Restore original message/body before handler RestoreOriginal(exchange, handler, originalBody, originalHeaders); // B5: OnPrepareFailure callback before handler/DLQ handler.OnPrepareFailure?.Invoke(exchange); if (handler.OnPrepareFailureProcessor is { } prepareFailure) await prepareFailure.Process(exchange, ct).ConfigureAwait(false); await handler.Processor.Process(exchange, ct).ConfigureAwait(false); // Apply handled/continued flags. // Handled or Continued suppress the failure — the exception is cleared and the consumer // commits. Otherwise — the // Camel handled(false) default — the failure is NOT suppressed: the onException route ran // (logging / DLQ / etc.), but the exception stays on the exchange with ExceptionHandled=false // so the consumer, which treats `Exception != null && !ExceptionHandled` as a failure, rolls // back and does not ack. Previously this branch set ExceptionHandled=true, silently swallowing // the failure: the transaction rolled back while the message was acknowledged. if (handler.Handled) { // Camel's ExchangeHelper.setFailureHandled: an error handler handled the failure. The exchange // completes successfully (the consumer acknowledges), but the idempotent consumer must not confirm // the key it claimed for the work that failed. exchange.MarkFailureHandled(); exchange.ExceptionHandled = true; exchange.Exception = null; } else if (handler.Continued) { // Camel's prepareExchangeForContinue clears the marker: a continued handler does not count the // failure handled, so a dedup key claimed for the block stays confirmed. exchange.ClearFailureHandled(); exchange.ExceptionHandled = true; exchange.Exception = null; } else { exchange.ClearFailureHandled(); exchange.ExceptionHandled = false; } // Continued: routing picks up at the step after the one that failed (Camel's continued(true)), where // Handled ends the route here. The next turn of the loop replays the steps the pipelines recorded, and // a failure among them is matched against the handlers anew. if (handler.Continued && !exchange.IsStopped) { continueAfter = ex; continue; } return; } } } private static void RestoreOriginal(IExchange exchange, ExceptionHandler handler, object? originalBody, IDictionary? originalHeaders) { if (handler.UseOriginalMessage && originalHeaders != null) { exchange.In.Body = originalBody; exchange.In.Headers.Clear(); foreach (var kvp in originalHeaders) exchange.In.Headers[kvp.Key] = kvp.Value; } else if (handler.UseOriginalBody) { exchange.In.Body = originalBody; } } /// /// The handler of this scope for and how far its type is from the exception it matched /// (0 — exactly that type), or no handler. See the class remarks for the rule. /// internal (ExceptionHandler? Handler, int Distance) FindHandler(Exception ex, IExchange exchange) { ExceptionHandler? best = null; var bestDistance = int.MaxValue; foreach (var failure in InnermostFirst(ex)) { var failureType = failure.GetType(); ExceptionHandler? candidate = null; var candidateDistance = int.MaxValue; foreach (var h in _handlers) { if (!h.ExceptionType.IsInstanceOfType(failure)) continue; if (h.OnWhenPredicate != null && !h.OnWhenPredicate(exchange)) continue; var distance = Distance(failureType, h.ExceptionType); if (distance < candidateDistance) { candidate = h; candidateDistance = distance; if (distance == 0) break; } } // The earlier exception of the walk keeps a tie. if (candidate is not null && candidateDistance < bestDistance) { best = candidate; bestDistance = candidateDistance; } if (bestDistance == 0) break; } return (best, bestDistance); } /// The failure and its causes, the innermost cause first, the thrown exception last. private static List InnermostFirst(Exception ex) { var chain = new List(); for (Exception? current = ex; current is not null; current = current.InnerException) chain.Add(current); chain.Reverse(); return chain; } /// How many base-type steps separate from . private static int Distance(Type failureType, Type handlerType) { var distance = 0; for (var type = failureType; type is not null && type != handlerType; type = type.BaseType) distance++; return distance; } /// Gets the registered handlers. public IReadOnlyList Handlers => _handlers; /// Describes a registered exception handler. /// Exception type to match. /// Handler processor to execute. /// Maximum redelivery attempts before handler fires. /// Optional retry policy for controlling delays between redeliveries. /// Whether the exception is marked as handled (clears Exception on exchange). /// Whether to continue the pipeline after handler. /// Guard predicate — handler fires only when this returns true. /// Log level for retry attempts. /// Log level when retries are exhausted. /// Callback invoked each time exception occurs. /// Predicate evaluated before each retry — continues retrying while true, regardless of max count. /// Callback invoked before each redelivery attempt (after delay). /// Callback invoked before the exchange is sent to the handler/DLQ after all retries are exhausted. /// When true, restore the original message (body + headers) before each retry and before executing the handler. /// When true, restore only the original body (not headers) before each retry and before executing the handler. /// When false (default), redelivery stops immediately if cancellation is requested. /// Whether to include the full stack trace in retry log messages (default: true). /// Whether to log when all retries are exhausted (default: true). /// Whether to log the exhausted failure when the handler handled it (default: false, as in Camel). /// Whether to log the exhausted failure when the handler continued it (default: false, as in Camel). public record ExceptionHandler( Type ExceptionType, IProcessor Processor, int MaxRedeliveries, RetryPolicy? RetryPolicy = null, bool Handled = false, bool Continued = false, Func? OnWhenPredicate = null, LogLevel RetryAttemptedLogLevel = LogLevel.Warning, LogLevel RetriesExhaustedLogLevel = LogLevel.Error, Action? OnExceptionOccurred = null, Func? RetryWhile = null, Action? OnRedelivery = null, Action? OnPrepareFailure = null, bool UseOriginalMessage = false, bool UseOriginalBody = false, bool AllowRedeliveryWhileStopping = false, bool LogStackTrace = true, bool LogExhausted = true, bool LogHandled = false, bool LogContinued = false) { /// Processor invoked every time the exception occurs, before any retry. public IProcessor? OnExceptionOccurredProcessor { get; init; } /// Processor invoked before each redelivery attempt. public IProcessor? OnRedeliveryProcessor { get; init; } /// Processor invoked before the handler runs, once the redeliveries are exhausted. public IProcessor? OnPrepareFailureProcessor { get; init; } } }