Created
November 16, 2023 16:53
-
-
Save defkode/d823d4720305b1fb13d26e66c7a94dac to your computer and use it in GitHub Desktop.
Retry n times on specified 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
# USAGE: retry 3 times on specified errors and wait 5s between retries | |
# when maximum retries is run then raise exception | |
# with_retries(on: [Errno::EHOSTUNREACH], tries: 3, interval: 5) do | |
# Net::HTTP.get('example.com', '/index.html') | |
# end | |
module WithRetries | |
def with_retries(on: [StandardError], tries: 3, interval: 0.5) | |
interval = 0 if Rails.env.test? # speed up tests | |
retries = 0 | |
begin | |
yield | |
rescue *on => e | |
if retries < tries | |
retries += 1 | |
Rails.logger.info "Retry ##{retries} due to error: #{e.class}" | |
sleep(interval) and retry | |
else | |
Rails.logger.info "Failed after #{retries} retries: #{e.class}" | |
raise | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment