rails begin exception retry

本文介绍了一种在Ruby中实现重试机制的方法,用于处理不稳定API调用导致的间歇性HTTP错误。通过定义retryable方法,可以指定重试次数及在哪些异常下触发重试,确保了网络请求的可靠性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I am not certain whether the ability to retry a code block when encountering exceptions was a feature available in Ruby, but I certainly couldn’t find anything on that topic (what I did find were mostly about the retry keyword for iterator loops).

Before you ask why I need this, the motivation for this was because I was getting intermittent HTTP errors (503s mostly) trying to connect to a web service. Turns out it’s really easy in Ruby to implement a retryable method that does something like this:

retryable(:tries => 5, :on => OpenURI::HTTPError) do
open('http://example.com/flaky_api')
# Code that mashes up stuff for your "social networking" site.
end


Here are the Kernel#retryable specs (pastie).

And the code:

# Options:
# * :tries - Number of retries to perform. Defaults to 1.
# * :on - The Exception on which a retry will be performed. Defaults to Exception, which retries on any Exception.
#
# Example
# =======
# retryable(:tries => 1, :on => OpenURI::HTTPError) do
# # your code here
# end
#
def retryable(options = {}, &block)
opts = { :tries => 1, :on => Exception }.merge(options)

retry_exception, retries = opts[:on], opts[:tries]

begin
return yield
rescue retry_exception
retry if (retries -= 1) > 0
end

yield
end


It’s not hard to implement the same for checking return values as well, i.e.

retryable_deluxe(:tries => 5, :on => { :return => nil }) { puts "working..." }

retryable_deluxe(:on => { :exception => StandardError, :return => nil }) do
# your code here
end


Ruby is nice.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值