Class: Bosh::Retryable

Inherits:
Object
  • Object
show all
Defined in:
lib/common/retryable.rb

Defined Under Namespace

Classes: ErrorMatcher

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Retryable

Returns a new instance of Retryable.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/common/retryable.rb', line 5

def initialize(options = {})
  opts = validate_options(options)

  @ensure_callback = opts[:ensure]
  @matching        = opts[:matching]
  @try_count       = 0
  @retry_exception = nil
  @retry_limit     = opts[:tries]
  @sleeper         = opts[:sleep]

  @matchers = Array(opts[:on]).map do |klass_or_matcher|
    if klass_or_matcher.is_a?(Class)
      ErrorMatcher.by_class(klass_or_matcher)
    else
      klass_or_matcher
    end
  end
end

Instance Method Details

#retryer(&blk) ⇒ Object

Loops until the block returns a true value



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/common/retryable.rb', line 25

def retryer(&blk)
  loop do
    @try_count += 1
    y = blk.call(@try_count, @retry_exception)
    @retry_exception = nil # no exception was raised in the block
    return y if y
    raise Bosh::Common::RetryCountExceeded if @try_count >= @retry_limit
    wait
  end
rescue Exception => exception
  raise unless @matchers.any? { |m| m.matches?(exception) }
  raise unless exception.message =~ @matching
  raise if @try_count >= @retry_limit

  @retry_exception = exception
  wait
  retry
ensure
  @ensure_callback.call(@try_count)
end