Timeout :: Error在Ruby中无法挽救

我对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

Timeout::ErrorTimeout::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

使用可重试使这变得简单

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/25873.html

上一篇: Timeout::Error isn't rescuing in Ruby

下一篇: How to handle errors/exceptions when calling an external API in Ruby on Rails?