加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

你如何在这个Ruby例子中限制重试和抢救?

发布时间:2020-12-16 21:38:06 所属栏目:百科 来源:网络整理
导读:在 Ruby的谦虚书中,提供了使用Rescue and retry的示例,它使用以下代码向服务器发送HTTP头: def make_request if (@http11) self.send('HTTP/1.1') else self.send('HTTP/1.0') endrescue ProtocolError @http11 = false retryend 为了限制一个无限循环,如果
在 Ruby的谦虚书中,提供了使用Rescue and 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

为了限制一个无限循环,如果它不能解决,我必须插入什么代码来重试5次?会是这样的:

5.times { retry }

解决方法

你可以在循环中写一个5倍的成功时间,但这是非常冗长的.在中/大脚本中,它应该是抽象的模式.例如,我们创建Object#with_rescue来保持内部逻辑与循环不同:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读