Skip to content

Commit

Permalink
Recursively search all AggregateException InnerExceptions for predica…
Browse files Browse the repository at this point in the history
…te matches when using HandleInner() App-vNext#818
  • Loading branch information
sideproject committed Jan 23, 2021
1 parent 52968c2 commit dd52d54
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
42 changes: 42 additions & 0 deletions src/Polly.Specs/Retry/RetrySpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,48 @@ public void Should_call_onretry_with_a_handled_innerexception()
passedToOnRetry.Should().BeSameAs(toRaiseAsInner);
}

[Fact]
public void Should_call_onretry_with_handled_exception_nested_in_aggregate_as_first_exception()
{
Exception passedToOnRetry = null;

var policy = Policy
.HandleInner<DivideByZeroException>()
.Retry(3, (exception, _) => passedToOnRetry = exception);

Exception toRaiseAsInner = new DivideByZeroException();

Exception aggregateException = new AggregateException(
new Exception("First: With Inner Exception",
toRaiseAsInner),
new Exception("Second: Without Inner Exception"));

policy.RaiseException(aggregateException);

passedToOnRetry.Should().BeSameAs(toRaiseAsInner);
}

[Fact]
public void Should_call_onretry_with_handled_exception_nested_in_aggregate_as_second_exception()
{
Exception passedToOnRetry = null;

var policy = Policy
.HandleInner<DivideByZeroException>()
.Retry(3, (exception, _) => passedToOnRetry = exception);

Exception toRaiseAsInner = new DivideByZeroException();

Exception aggregateException = new AggregateException(
new Exception("First: Without Inner Exception"),
new Exception("Second: With Inner Exception",
toRaiseAsInner));

policy.RaiseException(aggregateException);

passedToOnRetry.Should().BeSameAs(toRaiseAsInner);
}

[Fact]
public void Should_not_call_onretry_when_no_retries_are_performed()
{
Expand Down
9 changes: 7 additions & 2 deletions src/Polly/PolicyBuilder.OrSyntax.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,13 @@ internal static ExceptionPredicate HandleInner(Func<Exception, bool> predicate)
{
if (exception is AggregateException aggregateException)
{
Exception matchedInAggregate = aggregateException.Flatten().InnerExceptions.FirstOrDefault(predicate);
if (matchedInAggregate != null) return matchedInAggregate;
//search all inner exceptions wrapped inside the AggregateException recursively
foreach (var innerException in aggregateException.Flatten().InnerExceptions)
{
var matchedInAggregate = HandleInnerNested(predicate, innerException);
if (matchedInAggregate != null)
return matchedInAggregate;
}
}
return HandleInnerNested(predicate, exception);
Expand Down

0 comments on commit dd52d54

Please sign in to comment.