Path: redb-route/tests/redb.Route.Tests/Processors/OnExceptionProcessorTests.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/tests/redb.Route.Tests/Processors/OnExceptionProcessorTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using NSubstitute;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Definitions;
using redb.Route.Processors;
namespace redb.Route.Tests.Processors;
/// Tests for .
public class OnExceptionProcessorTests
{
/// Body executes normally when no exception.
[Fact]
public async Task Process_NoException_BodyExecutes()
{
var executed = false;
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => executed = true));
await processor.Process(new Exchange());
executed.Should().BeTrue();
}
/// Matching handler is invoked on exception.
[Fact]
public async Task Process_MatchingHandler_Invoked()
{
var handled = false;
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException("boom")))
.Handle(new DelegateProcessor(ex =>
{
handled = true;
ex.Exception.Should().BeOfType();
}));
var exchange = new Exchange();
await processor.Process(exchange);
handled.Should().BeTrue();
// handled:false (default) — the handler ran but the failure is NOT suppressed (Camel handled(false)),
// so the consumer (which checks Exception != null && !ExceptionHandled) still sees the failure.
exchange.ExceptionHandled.Should().BeFalse();
exchange.Exception.Should().NotBeNull();
}
/// No matching handler — exception rethrows.
[Fact]
public async Task Process_NoMatchingHandler_Rethrows()
{
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException()))
.Handle(new DelegateProcessor(_ => { }));
var act = () => processor.Process(new Exchange());
await act.Should().ThrowAsync();
}
/// Most-specific handler wins regardless of declaration order (Camel: nearest supertype).
[Fact]
public async Task Process_MostSpecificHandler_WinsRegardlessOfOrder()
{
string? picked = null;
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException("boom")))
// General handler declared FIRST, specific one SECOND — specificity must win, not order.
.Handle(new DelegateProcessor(_ => picked = "general"), handled: true)
.Handle(new DelegateProcessor(_ => picked = "specific"), handled: true);
await processor.Process(new Exchange());
picked.Should().Be("specific",
"the most-derived matching handler must win even when declared after the general one");
}
/// Redelivery retries before invoking handler.
[Fact]
public async Task Process_Redelivery_RetriesBeforeHandler()
{
var attempts = 0;
var body = new DelegateProcessor(_ =>
{
attempts++;
throw new InvalidOperationException($"attempt {attempts}");
});
var handled = false;
var processor = new OnExceptionProcessor(body, Substitute.For())
.Handle(
new DelegateProcessor(_ => handled = true),
maxRedeliveries: 2);
await processor.Process(new Exchange());
attempts.Should().Be(3); // 1 original + 2 redeliveries
handled.Should().BeTrue();
}
/// A genuine cancellation is never caught — the caller's token is what makes it one.
[Fact]
public async Task Process_CallerCancellation_NeverCaught()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new OperationCanceledException()))
.Handle(new DelegateProcessor(_ => { }));
var act = () => processor.Process(new Exchange(), cts.Token);
await act.Should().ThrowAsync();
}
/// A downstream timeout (an OperationCanceledException with our token still live) is named a
/// TimeoutException and reaches the handler.
[Fact]
public async Task Process_Timeout_HandledAsTimeoutException()
{
var handled = false;
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new TaskCanceledException("downstream deadline")))
.Handle(new DelegateProcessor(_ => handled = true), handled: true);
var exchange = new Exchange();
await processor.Process(exchange);
handled.Should().BeTrue();
exchange.ExceptionHandled.Should().BeTrue();
}
/// Handlers property returns registered handlers.
[Fact]
public void Handlers_ReturnsRegistered()
{
var processor = new OnExceptionProcessor(new DelegateProcessor(_ => { }))
.Handle(new DelegateProcessor(_ => { }))
.Handle(new DelegateProcessor(_ => { }));
processor.Handlers.Should().HaveCount(2);
}
// ── Handled flag ──
[Fact]
public async Task Handled_ClearsExceptionOnExchange()
{
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException("boom")))
.Handle(new DelegateProcessor(_ => { }),
handled: true);
var exchange = new Exchange();
await processor.Process(exchange);
exchange.ExceptionHandled.Should().BeTrue();
exchange.Exception.Should().BeNull("Handled flag should clear the exception");
}
[Fact]
public async Task Handled_False_ExceptionRemainsOnExchange()
{
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException("boom")))
.Handle(new DelegateProcessor(_ => { }),
handled: false);
var exchange = new Exchange();
await processor.Process(exchange);
exchange.ExceptionHandled.Should().BeFalse("Handled=false must not suppress the failure (Camel handled(false))");
exchange.Exception.Should().NotBeNull("Handled=false should keep exception on exchange");
}
// ── Continued flag ──
[Fact]
public async Task Continued_SetsExceptionHandled()
{
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException("boom")))
.Handle(new DelegateProcessor(_ => { }),
continued: true);
var exchange = new Exchange();
await processor.Process(exchange);
exchange.ExceptionHandled.Should().BeTrue();
exchange.Exception.Should().BeNull("Continued suppresses the exception and resumes routing");
}
// ── OnWhen predicate ──
[Fact]
public async Task OnWhen_True_HandlerFires()
{
var handled = false;
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException("boom")))
.Handle(new DelegateProcessor(_ => handled = true),
onWhenPredicate: ex => ex.Exception?.Message == "boom");
await processor.Process(new Exchange());
handled.Should().BeTrue();
}
[Fact]
public async Task OnWhen_False_HandlerSkipped_ExceptionRethrown()
{
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => throw new InvalidOperationException("boom")))
.Handle(new DelegateProcessor(_ => { }),
onWhenPredicate: _ => false);
var act = () => processor.Process(new Exchange());
await act.Should().ThrowAsync();
}
// ── OnExceptionOccurred callback ──
[Fact]
public async Task OnExceptionOccurred_CalledOnEachException()
{
var callbackCount = 0;
var attempts = 0;
var processor = new OnExceptionProcessor(
new DelegateProcessor(_ => { attempts++; throw new InvalidOperationException(); }))
.Handle(new DelegateProcessor(_ => { }),
maxRedeliveries: 2,
onExceptionOccurred: _ => callbackCount++);
await processor.Process(new Exchange());
callbackCount.Should().Be(3, "callback fires on each exception (1 original + 2 retries)");
}
// ── RetryAttemptedLogLevel / RetriesExhaustedLogLevel ──
[Fact]
public async Task CustomLogLevels_AreRespected()
{
var attempts = 0;
var body = new DelegateProcessor(_ =>
{
attempts++;
throw new InvalidOperationException($"attempt {attempts}");
});
// This test verifies the handler can be created with custom log levels without error
var processor = new OnExceptionProcessor(body)
.Handle(
new DelegateProcessor(_ => { }),
maxRedeliveries: 1,
retryAttemptedLogLevel: LogLevel.Debug,
retriesExhaustedLogLevel: LogLevel.Critical);
var exchange = new Exchange();
await processor.Process(exchange);
attempts.Should().Be(2); // 1 original + 1 retry
// handler is handled:false — after retries are exhausted the failure is not suppressed.
exchange.ExceptionHandled.Should().BeFalse();
}
// ── DSL integration: fluent chain scope ──
[Fact]
public async Task DslScope_Handled_ClearsException()
{
var context = new RouteContext();
object? captured = null;
context.AddRoutes(r =>
{
r.From("direct://oe-handled")
.OnException()
.Handled()
.Log("Handled!")
.End()
.Process(_ => throw new InvalidOperationException("test"))
.Process(e => captured = "should-not-reach");
});
await context.Start();
try
{
var producer = context.GetEndpoint("direct://oe-handled").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("data"));
await producer.Process(exchange);
exchange.ExceptionHandled.Should().BeTrue();
exchange.Exception.Should().BeNull();
}
finally
{
await context.Stop();
}
}
[Fact]
public async Task DslScope_OnWhen_FiltersHandler()
{
var fallbackReached = false;
var context = new RouteContext();
context.AddRoutes(r =>
{
r.From("direct://oe-onwhen")
.OnException()
.OnWhen(e => e.Exception?.Message == "expected")
.Handled()
.Process(_ => fallbackReached = true)
.End()
.Process(_ => throw new InvalidOperationException("expected"));
});
await context.Start();
try
{
var producer = context.GetEndpoint("direct://oe-onwhen").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("data"));
await producer.Process(exchange);
fallbackReached.Should().BeTrue();
exchange.ExceptionHandled.Should().BeTrue();
}
finally
{
await context.Stop();
}
}
[Fact]
public async Task DslScope_OnExceptionOccurred_CallbackInvoked()
{
var callbackCount = 0;
var context = new RouteContext();
context.AddRoutes(r =>
{
r.From("direct://oe-callback")
.OnException()
.Handled()
.MaximumRedeliveries(1)
.RedeliveryDelay(TimeSpan.FromMilliseconds(1))
.OnExceptionOccurred(_ => callbackCount++)
.End()
.Process(_ => throw new InvalidOperationException("test"));
});
await context.Start();
try
{
var producer = context.GetEndpoint("direct://oe-callback").CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("data")));
callbackCount.Should().Be(2, "callback fires on original + 1 retry");
}
finally
{
await context.Stop();
}
}
[Fact]
public async Task DslScope_RetryLogLevels_Configurable()
{
var context = new RouteContext();
context.AddRoutes(r =>
{
r.From("direct://oe-loglevels")
.OnException()
.Handled()
.MaximumRedeliveries(1)
.RedeliveryDelay(TimeSpan.FromMilliseconds(1))
.RetryAttemptedLogLevel(LogLevel.Debug)
.RetriesExhaustedLogLevel(LogLevel.Critical)
.End()
.Process(_ => throw new InvalidOperationException("test"));
});
await context.Start();
try
{
var producer = context.GetEndpoint("direct://oe-loglevels").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("data"));
await producer.Process(exchange);
// Simply verifies that custom log levels don't break anything
exchange.ExceptionHandled.Should().BeTrue();
}
finally
{
await context.Stop();
}
}
[Fact]
public void DslScope_HandledOutsideScope_Throws()
{
var def = new RouteDefinition();
var act = () => def.Handled();
act.Should().Throw()
.WithMessage("*OnException*");
}
[Fact]
public void DslScope_ContinuedOutsideScope_Throws()
{
var def = new RouteDefinition();
var act = () => def.Continued();
act.Should().Throw()
.WithMessage("*OnException*");
}
[Fact]
public void DslScope_OnWhenOutsideScope_Throws()
{
var def = new RouteDefinition();
var act = () => def.OnWhen(_ => true);
act.Should().Throw()
.WithMessage("*OnException*");
}
// ── B3: RetryWhile predicate ──
[Fact]
public async Task RetryWhile_ContinuesWhileTrue()
{
var attempts = 0;
var body = new DelegateProcessor(_ =>
{
attempts++;
throw new InvalidOperationException($"attempt {attempts}");
});
var processor = new OnExceptionProcessor(body, Substitute.For())
.Handle(
new DelegateProcessor(_ => { }),
handled: true,
retryWhile: ex => attempts < 4, // retry while attempts < 4
redeliveryDelay: TimeSpan.FromMilliseconds(1));
await processor.Process(new Exchange());
attempts.Should().Be(4, "RetryWhile should keep retrying until predicate returns false");
}
[Fact]
public async Task RetryWhile_OverridesMaxRedeliveries()
{
var attempts = 0;
var body = new DelegateProcessor(_ =>
{
attempts++;
throw new InvalidOperationException();
});
// MaxRedeliveries=1 but RetryWhile says keep going until 5
var processor = new OnExceptionProcessor(body, Substitute.For())
.Handle(
new DelegateProcessor(_ => { }),
handled: true,
maxRedeliveries: 1,
retryWhile: _ => attempts < 5,
redeliveryDelay: TimeSpan.FromMilliseconds(1));
await processor.Process(new Exchange());
attempts.Should().Be(5, "RetryWhile takes priority over MaxRedeliveries");
}
// ── B4: OnRedelivery callback ──
[Fact]
public async Task OnRedelivery_CalledBeforeEachRetry()
{
var redeliveryCalls = 0;
var attempts = 0;
var body = new DelegateProcessor(_ =>
{
attempts++;
throw new InvalidOperationException();
});
var processor = new OnExceptionProcessor(body, Substitute.For())
.Handle(
new DelegateProcessor(_ => { }),
handled: true,
maxRedeliveries: 3,
redeliveryDelay: TimeSpan.FromMilliseconds(1),
onRedelivery: _ => redeliveryCalls++);
await processor.Process(new Exchange());
redeliveryCalls.Should().Be(3, "OnRedelivery fires before each of the 3 retries");
}
// ── B5: OnPrepareFailure callback ──
[Fact]
public async Task OnPrepareFailure_CalledBeforeHandler()
{
var prepareCalled = false;
var body = new DelegateProcessor(_ => throw new InvalidOperationException());
var processor = new OnExceptionProcessor(body)
.Handle(
new DelegateProcessor(_ => { }),
handled: true,
onPrepareFailure: ex =>
{
prepareCalled = true;
ex.In.Headers["PreparedForFailure"] = true;
});
var exchange = new Exchange();
await processor.Process(exchange);
prepareCalled.Should().BeTrue();
exchange.In.Headers.Should().ContainKey("PreparedForFailure");
}
// ── B6: UseOriginalMessage / UseOriginalBody ──
[Fact]
public async Task UseOriginalBody_RestoresBodyBeforeHandler()
{
var body = new DelegateProcessor(ex =>
{
ex.In.Body = "mutated";
throw new InvalidOperationException();
});
object? handlerBody = null;
var processor = new OnExceptionProcessor(body)
.Handle(
new DelegateProcessor(ex => handlerBody = ex.In.Body),
handled: true,
useOriginalBody: true);
var exchange = new Exchange(new Message("original"));
await processor.Process(exchange);
handlerBody.Should().Be("original", "UseOriginalBody should restore body before handler");
}
[Fact]
public async Task UseOriginalMessage_RestoresBodyAndHeaders()
{
var body = new DelegateProcessor(ex =>
{
ex.In.Body = "mutated";
ex.In.Headers["NewHeader"] = "added";
throw new InvalidOperationException();
});
object? handlerBody = null;
bool? hasNewHeader = null;
var processor = new OnExceptionProcessor(body)
.Handle(
new DelegateProcessor(ex =>
{
handlerBody = ex.In.Body;
hasNewHeader = ex.In.Headers.ContainsKey("NewHeader");
}),
handled: true,
useOriginalMessage: true);
var exchange = new Exchange(new Message("original"));
exchange.In.Headers["OriginalHeader"] = "kept";
await processor.Process(exchange);
handlerBody.Should().Be("original");
hasNewHeader.Should().BeFalse("UseOriginalMessage should restore original headers, removing added ones");
}
// ── B7: AllowRedeliveryWhileStopping ──
[Fact]
public async Task AllowRedeliveryWhileStopping_False_StopsRetryOnCancellation()
{
var attempts = 0;
var cts = new CancellationTokenSource();
var body = new DelegateProcessor(_ =>
{
attempts++;
if (attempts == 1)
cts.Cancel(); // cancel after first attempt
throw new InvalidOperationException();
});
var handlerCalled = false;
var processor = new OnExceptionProcessor(body, Substitute.For())
.Handle(
new DelegateProcessor(_ => handlerCalled = true),
handled: true,
maxRedeliveries: 5,
redeliveryDelay: TimeSpan.FromMilliseconds(1),
allowRedeliveryWhileStopping: false);
// The cts.Cancel() triggers OperationCanceledException in Task.Delay
// But since AllowRedeliveryWhileStopping=false, shouldRetry becomes false,
// so it goes to exhaustion path (handler should fire)
await processor.Process(new Exchange(), cts.Token);
attempts.Should().Be(1, "should stop retrying after cancellation");
handlerCalled.Should().BeTrue("handler fires after retries are refused");
}
// ── B8: LogStackTrace / LogExhausted ──
[Fact]
public async Task LogExhausted_False_SuppressesExhaustionLog()
{
var logger = Substitute.For();
var body = new DelegateProcessor(_ => throw new InvalidOperationException());
var processor = new OnExceptionProcessor(body, logger)
.Handle(
new DelegateProcessor(_ => { }),
handled: true,
maxRedeliveries: 1,
redeliveryDelay: TimeSpan.FromMilliseconds(1),
logExhausted: false);
await processor.Process(new Exchange());
// Logger should NOT receive an Error-level "Retries exhausted" message
// (it may still receive Warning-level retry attempt messages)
logger.ReceivedCalls()
.Where(c => c.GetMethodInfo().Name == "Log")
.SelectMany(c => c.GetArguments())
.OfType()
.Should().NotContain(LogLevel.Error);
}
// ── LogHandled / LogContinued (Camel's logHandled / logContinued) ──
/// The argument list of every Log call a substitute logger received.
private static IReadOnlyList