超时::错误不是在Ruby中拯救

时间:2012-08-02 03:12:47

标签: ruby http timeout

我还是Ruby的新手,我第一次尝试将Timeout用于某些HTTP功能,但显然我在某个地方错过了标记。我的代码如下,但它不起作用。相反,它引发了以下异常:

C:/Ruby193/lib/ruby/1.9.1/net/http.rb:762:in `initialize': execution expired (Timeout::Error)

这对我来说没有多大意义,因为它的超时代码部分包含在begin / rescue / end块中,特别是救出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

2 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:3)

使用retryable来实现这个简单的

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