在这个Ruby示例中,如何限制重试和救援?

Sim*_*ton 15 ruby

在简陋的Ruby书中,提供了使用Rescue和retry的示例,使用以下代码将HTTP标头发送到服务器:

def make_request
  if (@http11)
    self.send('HTTP/1.1')
  else
    self.send('HTTP/1.0')
  end
rescue ProtocolError
  @http11 = false
  retry
end
Run Code Online (Sandbox Code Playgroud)

要限制一个无限循环以防它无法解析,我必须插入什么代码才能重试5次?会是这样的:

5.times { retry }
Run Code Online (Sandbox Code Playgroud)

tok*_*and 19

你可以在循环中写一个成功的5.times加号break,或者抽象模式以使逻辑与循环分开.一个主意:

module Kernel
  def with_rescue(exceptions, retries: 5)
    try = 0
    begin
      yield try
    rescue *exceptions => exc
      try += 1
      try <= retries ? retry : raise
    end
  end
end

with_rescue([ProtocolError], retries: 5) do |try|
  protocol = (try == 0) ? 'HTTP/1.1' : 'HTTP/1.0'
  send(protocol)
end
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是一个古老的答案,但[可重复的宝石](https://github.com/kamui/retriable)基本上完成了这个问题. (3认同)

Sam*_*uel 5

我使用此函数以间歇性延迟运行和重试命令有限的次数。事实证明,tries参数可以简单地在函数体中增加,并在retry被调用时传递。

def run_and_retry_on_exception(cmd, tries: 0, max_tries: 3, delay: 10)
  tries += 1
  run_or_raise(cmd)
rescue SomeException => exception
  report_exception(exception, cmd: cmd)
  unless tries >= max_tries
    sleep delay
    retry
  end
end
Run Code Online (Sandbox Code Playgroud)