Skip to content

Instantly share code, notes, and snippets.

@sparrovv
Created December 4, 2011 20:16
Show Gist options
  • Save sparrovv/1431162 to your computer and use it in GitHub Desktop.
Save sparrovv/1431162 to your computer and use it in GitHub Desktop.
retry code if case of some specific exception
# I don't remember where I found it but it's useful in case of errors like: Net::HTTP::Persistent::Error: too many connection resets...
module Kernel
# Options
# =======
# * :tries Number of retries to perform. Defaults to 1.
# Note this means it actually tries 2 times!
# * :on - The Exception on which a retry will be performed. Defaults to
# Exception, which retries on any Exception.
# * :delay - Delay in seconds before the next try (optional)
#
# * :before - if some asset requires reloading put in lambda, and it'll be called before retryging # Example
# =======
# retryable(:tries => 1, :on => OpenURI::HTTPError) do
# # your code here
# end
#
def retryable(options = {}, &block)
opts = { :tries => 1, :on => Exception }.merge(options)
retry_exception, retries, delay, before = opts[:on], opts[:tries], opts[:delay], opts[:before]
begin
return yield
rescue retry_exception => e
Rails.logger.info("Retries #{retries}: #{e.class} - #{e.message}")
before.call if before.respond_to?(:call)
sleep delay unless delay.nil?
retry if (retries -= 1) > 0
end
yield
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment