Module: Take2::InstanceMethods
- Defined in:
- lib/take2.rb
Instance Method Summary collapse
-
#call_api_with_retry(options = {}) ⇒ Object
Yields a block and retries on retriable errors n times.
Instance Method Details
#call_api_with_retry(options = {}) ⇒ Object
Yields a block and retries on retriable errors n times. The raised error could be the defined retriable or it child.
Example:
class PizzaService
include Take2
number_of_retries 3
retriable_errors Net::HTTPRetriableError
retriable_condition proc { |error| response_status(error.response) < 500 }
on_retry proc { |error, tries| puts "#{self.name} - Retrying.. #{tries} of #{self.retriable_configuration[:retries]} (#{error})" }
sleep_before_retry 3
def give_me_food
call_api_with_retry do
# Some logic that might raise..
# If it will raise retriable, magic happens.
# If not the original error re raised
end
end
end
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/take2.rb', line 58 def call_api_with_retry( = {}) config = self.class.retriable_configuration config.merge! Take2.local_defaults() unless .empty? tries ||= config[:retries] begin yield rescue => e if config[:retriable].map {|klass| e.class <= klass }.any? unless tries.zero? || config[:retry_condition_proc]&.call(e) config[:retry_proc]&.call(e, tries) sleep(config[:time_to_sleep]) if config[:time_to_sleep] tries -= 1 retry end end raise e end end |