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
The Timeout::Error
is getting raised in the call to Timeout::timeout
, so you need to put that inside the 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With