class Fixnum

Public Instance Methods

attempts(exception_list=StandardError, delay=1) { |count| ... } click to toggle source

AWS is often unreliable, so this method provides an easy way of calling a block of code multiple times and ignoring exceptions of the classes named in exception_list. exception_list may be a single Exception object or an Array of Exception objects.

Any such exceptions raised during the first n - 1 iterations are ignored and a period of delay seconds is inserted before each retry. If the block still yields a listed exception on the _n_th pass, that exception will be raised. The default exception class of StandardError will catch this class and all of its subclasses, which includes all exception classes that Ruby/Amazon defines.

For example, the following code makes 3 attempts to retrieve all pages for a given wishlist:

require 'amazon/search'
include Amazon::Search

req = Request.new('D23XFCO2UKJY82')

resp = 3.attempts do |x|
  puts "Attempt #{x}..."
  req.wishlist_search('RMPWOC6X3DLC', LITE, ALL_PAGES)
end

puts resp.products
# File lib/amazon.rb, line 276
def attempts(exception_list=StandardError, delay=1)
  return if self <= 0

  result = nil

  count = 0
  loop do

    begin
      reason = nil
      result = yield(count += 1)
    rescue *exception_list => reason
      if count < self
        sleep delay
        retry
      end
    end

    if reason
      raise reason
    else
      return result
    end

  end
end