在
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