我对 Ruby 还是个新手,这是我第一次尝试将超时用于某些 HTTP 函数,但显然我在某处遗漏了标记。我的代码在下面,但它不工作。相反,它会引发以下异常:
C:/Ruby193/lib/ruby/1.9.1/net/http.rb:762:in `initialize': execution expired (Timeout::Error)
这对我来说意义不大,因为它超时的代码部分包含在开始/救援/结束 block 中,专门用于救援 Timeout::Error。我做错了什么,或者 Ruby 不支持什么?
retries = 10
Timeout::timeout(5) do
begin
File.open("#{$temp}\\http.log", 'w') { |f|
http.request(request) do |str|
f.write str.body
end
}
rescue Timeout::Error
if retries > 0
print "Timeout - Retrying..."
retries -= 1
retry
else
puts "ERROR: Not responding after 10 retries! Giving up!")
exit
end
end
end
最佳答案
Timeout::Error
在 Timeout::timeout
的调用中被引发,所以你需要把它放在 begin
中 block :
retries = 10
begin
Timeout::timeout(5) do
File.open("#{$temp}\\http.log", 'w') do |f|
http.request(request) do |str|
f.write str.body
end
end
end
rescue Timeout::Error
if retries > 0
print "Timeout - Retrying..."
retries -= 1
retry
else
puts "ERROR: Not responding after 10 retries! Giving up!")
exit
end
end
关于ruby - Timeout::Error 不是在 Ruby 中拯救,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11770535/