Last active
November 28, 2017 14:32
-
-
Save atheiman/33f870cf850358701a8dbd4fd965d5a2 to your computer and use it in GitHub Desktop.
Execute a block with retries for exceptions
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
def doubles? | |
a = rand(1..6) | |
b = rand(1..6) | |
puts "#{a} and #{b}" | |
raise 'Not doubles!' unless a == b | |
true | |
end | |
def with_retries(retries: 2, sleep: 1) | |
attempt = 1 | |
begin | |
puts "attempt #{attempt}" | |
value = yield | |
rescue LocalJumpError => e # error for no block given | |
raise e | |
rescue StandardError => e # all other errors | |
puts "attempt #{attempt} failed!" | |
if (attempt += 1) <= (retries + 1) | |
Kernel.sleep(sleep) | |
retry | |
end | |
raise e | |
end | |
puts "attempt #{attempt} succeeded!" | |
value | |
end | |
with_retries { doubles? } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment