Last active
December 12, 2015 12:49
-
-
Save zachbonham/4774553 to your computer and use it in GitHub Desktop.
Retriable implementation in PowerShell completely ripped off from an implementation in Ruby.
This file contains hidden or 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
# complete rip off of http://blog.mirthlab.com/2012/05/25/cleanly-retrying-blocks-of-code-after-an-exception-in-ruby/ | |
# | |
# usage | |
# retriable -tries 5 -action { do-work-that-could-throw-exception } | |
# | |
function retriable($tries=3, $interval=1, [scriptblock]$action) | |
{ | |
$retry_count = 1 | |
$the_exception = $null | |
do | |
{ | |
$is_error = $false | |
try | |
{ | |
& $action | |
# reset in case it worked this last try | |
# | |
$is_error = $false | |
} | |
catch | |
{ | |
#cache off exception to throw if we've exhausted our retries | |
# | |
$the_exception = $_ | |
$is_error = $true | |
write-debug "[retriable] caught exception" | |
write-debug "[retriable] attempt $retry_count of $tries failed, trying again" | |
if ( $retry_count -ge $tries ) | |
{ | |
write-debug "[retriable] exhausted $retry_count retry attempts" | |
} | |
else | |
{ | |
write-debug "[retriable] waiting $interval seconds" | |
sleep -seconds $interval | |
} | |
} | |
$retry_count = $retry_count + 1 | |
} while($is_error -eq $true -and $retry_count -le $tries) | |
if ( $is_error ) | |
{ | |
throw $the_exception | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment