Created
September 11, 2016 06:24
-
-
Save jpv001/721f11574d3fdac67b07f1c514defae0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var policy = Policy | |
.Handle<TimeoutException>() | |
.Or<SqlException>(ex => (new[] { 40613, 40501, 40197, 10929, 10928, 10060, 10054, 10053, 233, 64, 20 }).Contains(ex.Number)) | |
.WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt) / 2), | |
(ex, count) => | |
{ | |
count.Dump(); | |
//log | |
}); | |
var test = new SqlConnFailureTester(); | |
policy.Execute(() => test.ThrowsATransientError().Dump()); | |
} | |
public class SqlConnFailureTester | |
{ | |
private int FailureTriggered { get; set;} = 0; | |
public string ThrowsATimeoutError() | |
{ | |
if(FailureTriggered > 0) return $"Success after {FailureTriggered} failures"; | |
FailureTriggered++; | |
throw new TimeoutException(); | |
} | |
public string ThrowsATransientError() | |
{ | |
if(FailureTriggered > 0) return $"Success after {FailureTriggered} failures"; | |
FailureTriggered++; | |
throw CreateSqlException(20); | |
} | |
private SqlException CreateSqlException(int number) | |
{ | |
var collectionConstructor = typeof(SqlErrorCollection).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null); | |
var addMethod = typeof(SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance); | |
var errorCollection = (SqlErrorCollection)collectionConstructor.Invoke(null); | |
var errorConstructor = typeof(SqlError).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] | |
{ | |
typeof (int), typeof (byte), typeof (byte), typeof (string), typeof(string), typeof (string), | |
typeof (int), typeof (uint) | |
}, null); | |
var error = errorConstructor.Invoke(new object[] { number, (byte)0, (byte)0, "server", "errMsg", "proccedure", 100, (uint)0 }); | |
addMethod.Invoke(errorCollection, new[] { error }); | |
var constructor = typeof(SqlException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] | |
{ | |
typeof(string), typeof(SqlErrorCollection), typeof(Exception), typeof(Guid) | |
}, null); | |
return (SqlException)constructor.Invoke(new object[] { "Error message", errorCollection, new DataException(), Guid.NewGuid() }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment