PolicyBuilder
Builder class that holds the list of current exception predicates.
using System;
using System.ComponentModel;
using System.Linq;
namespace Polly
{
public sealed class PolicyBuilder
{
internal ExceptionPredicates ExceptionPredicates { get; }
internal PolicyBuilder(ExceptionPredicate exceptionPredicate)
{
ExceptionPredicates = new ExceptionPredicates();
ExceptionPredicates.Add(exceptionPredicate);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString()
{
return base.ToString();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
return base.GetHashCode();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new Type GetType()
{
return base.GetType();
}
public PolicyBuilder Or<TException>() where TException : Exception
{
ExceptionPredicates.Add(delegate(Exception exception) {
if (!(exception is TException))
return null;
return exception;
});
return this;
}
public PolicyBuilder Or<TException>(Func<TException, bool> exceptionPredicate) where TException : Exception
{
ExceptionPredicates.Add(delegate(Exception exception) {
TException val = exception as TException;
if (val == null || !exceptionPredicate(val))
return null;
return exception;
});
return this;
}
public PolicyBuilder OrInner<TException>() where TException : Exception
{
ExceptionPredicates.Add(HandleInner((Exception ex) => ex is TException));
return this;
}
public PolicyBuilder OrInner<TException>(Func<TException, bool> exceptionPredicate) where TException : Exception
{
ExceptionPredicates.Add(HandleInner(delegate(Exception exception) {
TException val = exception as TException;
if (val != null)
return exceptionPredicate(val);
return false;
}));
return this;
}
internal static ExceptionPredicate HandleInner(Func<Exception, bool> predicate)
{
return delegate(Exception exception) {
AggregateException ex = exception as AggregateException;
if (ex != null) {
Exception ex2 = ex.Flatten().InnerExceptions.FirstOrDefault(predicate);
if (ex2 != null)
return ex2;
}
return HandleInnerNested(predicate, exception);
};
}
private static Exception HandleInnerNested(Func<Exception, bool> predicate, Exception current)
{
if (current == null)
return null;
if (predicate(current))
return current;
return HandleInnerNested(predicate, current.InnerException);
}
public PolicyBuilder<TResult> OrResult<TResult>(Func<TResult, bool> resultPredicate)
{
return new PolicyBuilder<TResult>(ExceptionPredicates).OrResult(resultPredicate);
}
public PolicyBuilder<TResult> OrResult<TResult>(TResult result)
{
return OrResult(delegate(TResult r) {
if (r == null || !r.Equals(result)) {
if (r == null)
return result == null;
return false;
}
return true;
});
}
}
}