Path: redb-route/redb.Route/ErrorHandling/DeadLetterErrorHandler.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/ErrorHandling/DeadLetterErrorHandler.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Telemetry;
namespace redb.Route.ErrorHandling;
///
/// The context's dead letter channel — Apache Camel's errorHandler(deadLetterChannel("direct:errors")) at the
/// CamelContext level: set as , it takes every failure of every route that no
/// OnException took, stamps it with the CamelDeadLetter* headers and sends it to the dead letter endpoint
/// (usually a route of its own, direct:errors). A delivered exchange is handled — the failure does not go on to
/// the caller, as with Camel's dead letter channel. A failed delivery is logged and the failure goes on.
///
/// Redeliveries are the business of OnException (MaximumRedeliveries, RetryWhile): an error
/// handler receives a failure after the step that threw has returned and has nothing to run again.
///
///
public sealed class DeadLetterErrorHandler : IErrorHandler
{
private readonly IProcessor _deadLetter;
private readonly ILogger? _logger;
/// Creates the dead letter channel of .
/// The context whose endpoint receives the dead letters.
/// The dead letter endpoint, e.g. direct://errors.
/// Optional logger.
public DeadLetterErrorHandler(IRouteContext context, string deadLetterUri, ILogger? logger = null)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentException.ThrowIfNullOrWhiteSpace(deadLetterUri);
DeadLetterUri = deadLetterUri;
_deadLetter = new ToProcessor(deadLetterUri, context);
_logger = logger;
}
/// The dead letter endpoint.
public string DeadLetterUri { get; }
///
public async Task HandleError(IExchange exchange, Exception exception, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(exchange);
ArgumentNullException.ThrowIfNull(exception);
DeadLetterHeaders.Stamp(exchange, exception, 0);
_logger?.LogError(exception, "Dead-lettering exchange {ExchangeId} to {Uri}.",
exchange.ExchangeId, EndpointUri.Sanitize(DeadLetterUri));
try
{
await _deadLetter.Process(exchange, ct).ConfigureAwait(false);
ProcessorMetrics.DeadLetterSent.Add(1);
exchange.ExceptionHandled = true;
}
catch (Exception sendFailure) when (!RouteCancellation.IsCancellation(sendFailure, ct))
{
// The dead letter is lost: the original failure goes on to the caller rather than being swallowed.
_logger?.LogError(sendFailure, "Dead-letter delivery to {Uri} failed.", EndpointUri.Sanitize(DeadLetterUri));
}
}
}