Created
February 8, 2021 23:10
-
-
Save jbranchaud/629fb3b9d55c817e5c9fc480790dfabc to your computer and use it in GitHub Desktop.
Ruby's rescue exception and retry functionality
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 sometimes_fails | |
puts "Beginning of sometimes_fails" | |
begin | |
retries ||= 0 | |
puts "About to do a thing (#{retries})" | |
raise StandardError if rand(5) != 4 | |
puts "Success!" | |
rescue StandardError => e | |
retry if (retries += 1) < 3 | |
# all retries failed, re-raise exception | |
raise e | |
end | |
end | |
sometimes_fails | |
# A run where the retries eventually succeed: | |
# | |
# > ruby retry.rb | |
# Beginning of sometimes_fails | |
# About to do a thing (0) | |
# About to do a thing (1) | |
# About to do a thing (2) | |
# Success! | |
# A run where the retries run out: | |
# | |
# > ruby retry.rb | |
# Beginning of sometimes_fails | |
# About to do a thing (0) | |
# About to do a thing (1) | |
# About to do a thing (2) | |
# Traceback (most recent call last): | |
# 1: from retry.rb:17:in `<main>' | |
# retry.rb:6:in `sometimes_fails': StandardError (StandardError) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment