【问题标题】:Timeout::Error isn't rescuing in RubyTimeout::Error 没有在 Ruby 中拯救
【发布时间】:2012-07-31 00:22:16
【问题描述】:

我还是 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

【问题讨论】:

    标签: ruby http timeout


    【解决方案1】:

    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
    

    【讨论】:

    • 成功了。哇,谢谢你的快速回复。我认为那是愚蠢的,但我仍然习惯了 Ruby,并且像这样的地方提供的帮助对我有很大帮助。谢谢!
    • @FliptDoubt 没问题,如果这回答了你的问题,别忘了upvote/accept it:)
    • 太棒了!非常喜欢它。
    【解决方案2】:

    使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 2013-06-28
      • 1970-01-01
      • 2010-10-07
      • 2011-01-12
      • 2012-07-11
      • 2010-12-15
      相关资源
      最近更新 更多