Timeout::Error isn't rescuing in Ruby
I am still new with Ruby and for the first time I'm trying to use Timeout for some HTTP functions but clearly I'm missing the mark somewhere. My code is below but it's not working. Instead, it raises the following exception:
C:/Ruby193/lib/ruby/1.9.1/net/http.rb:762:in `initialize': execution expired (Timeout::Error)
Which doesn't make a lot of sense to me since the part of the code it's timing out on is wrapped in a begin/rescue/end block and specifically rescues Timeout::Error. Am I doing something wrong, or something that isn't supported in 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
块中:
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
Use retryable to make this simple
https://github.com/nfedyashev/retryable#readme
require "open-uri"
retryable(:tries => 3, :on => OpenURI::HTTPError) do
xml = open("http://example.com/test.xml").read
end
链接地址: http://www.djcxy.com/p/25874.html
上一篇: 如何通过一条救援声明尽快捕获所有异常