I’m having trouble performing a simple test of the Transient Fault Handling Application Block, so I must be missing something silly.
Based on the information in http://msdn.microsoft.com/en-us/library/hh680927(v=pandp.50).aspx and
http://azuretable.blogspot.com/2012/08/unit-testing-transient-errors-in-azure.html I have created the mock class below:
Public Class DBUtils_TestRetryPolicy
' see http://msdn.microsoft.com/en-us/library/hh680927(v=pandp.50).aspx
' see http://azuretable.blogspot.com/2012/08/unit-testing-transient-errors-in-azure.html
Public Class TransientMock
Implements ITransientErrorDetectionStrategy
Public Function IsTransient(ex As System.Exception) As Boolean Implements Microsoft.Practices.TransientFaultHandling.ITransientErrorDetectionStrategy.IsTransient
Return (True)
End Function
End Class
Private Shared mockExceptionCounter As Integer = 0
Private Shared retryLog As String = ""
Private Sub ThrowException()
mockExceptionCounter += 1
Throw New Exception("This is as mock exception to test retries")
End Sub
Public Function TestRetryLogic() As String
Dim theRetryStrategy = New Incremental(6, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)) ' should result in retries at 0, 1, 3, 5, 7, 9 seconds (25 seconds total)
theRetryStrategy.FastFirstRetry = True
Dim theRetryPolicy = New RetryPolicy(Of TransientMock)(theRetryStrategy)
AddHandler theRetryPolicy.Retrying, AddressOf OnMockConnectionRetry
mockExceptionCounter = 0
retryLog = ""
Try
theRetryPolicy.ExecuteAction(New System.Action(AddressOf ThrowException))
Catch ex As Exception
' here we should have the last exception thrown after all the retries
Dim a As Integer = 231234234
End Try
Return (retryLog)
End Function
Private Sub OnMockConnectionRetry(sender As Object, e As RetryingEventArgs)
retryLog += DateTime.UtcNow.ToString + " [" + mockExceptionCounter.ToString() + "] -> CurrentRetryCount [" + Cstr(e.CurrentRetryCount) + "]" + "Delay (ms) [" + CStr(e.Delay.TotalMilliseconds) + "]" + "LastException [" + e.LastException.Message + "]"
End Sub
End Class
All I do in my code is to instantiate this class and call TestRetryLogic().
I ran the Visual Studio debugger expecting to see a few retries, but what I get is a popup from Visual Studio saying “Exception was unhandled by user code”. This happens as soon as I throw inside the method ThrowException(). Of course no retries seem to be happening.
What am I missing?
EDIT: I was failing to cast to string inside OnMockConnectionRetry, so I assume I was throwing an exception inside an (already “running”) exception-handling block. By using the tip from Petar I was able to see (and fix) this little problem and now the retries are working as expected.
You need to turn off Common Language Runtime Exceptions by un-checking the User-unhandled option to not get interrupted by VS. This is located under Debug/Exceptions menu.