Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout::Error isn't rescuing in Ruby

Tags:

http

ruby

timeout

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
like image 920
Flipt Doubt Avatar asked Aug 02 '12 03:08

Flipt Doubt


2 Answers

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
like image 133
Andrew Marshall Avatar answered Nov 17 '22 21:11

Andrew Marshall


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
like image 35
crazycrv Avatar answered Nov 17 '22 20:11

crazycrv