5

我还是 Ruby 的新手,我第一次尝试将 Timeout 用于某些 HTTP 函数,但显然我在某处遗漏了标记。我的代码在下面,但它不起作用。相反,它引发了以下异常:

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

这对我来说没有多大意义,因为它超时的代码部分被包装在开始/救援/结束块中,并专门救援 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
4

2 回答 2

22

在对的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
于 2012-08-02T03:21:06.767 回答
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
于 2013-06-11T12:08:16.060 回答