Ruby curb (libcurl): 测试 GET 请求超时

Ruby curb (libcurl): testing for time-out in GET request

使用 curb gem (https://github.com/taf2/curb) 从 REST API.

GET
  resp = Curl.get("http://someurl.com/users.json") do |http|
    http.headers["API-Key"] = ENV["API_KEY"]
  end
  # do stuff with resp.body_str

我开始遇到 Curl.get 的偶尔超时问题。

想在我尝试的地方添加逻辑GET:如果请求超时,我们再试一次,即

loop do
  resp = Curl.get("http://someurl.com/users.json") do |http|
    http.headers["API-Key"] = ENV["API_KEY"]
  end

  # test result of Curl.get
  # if time-out, then then try again
end

无法find/figure了解如何测试超时结果。

我错过了什么?

已更新:添加了异常详细信息

Curl::Err::TimeoutError: Timeout was reached
/app/vendor/bundle/ruby/2.3.0/gems/curb-0.9.3/lib/curl/easy.rb:73:in `perform'
/app/vendor/bundle/ruby/2.3.0/gems/curb-0.9.3/lib/curl.rb:17:in `http'
/app/vendor/bundle/ruby/2.3.0/gems/curb-0.9.3/lib/curl.rb:17:in `http'
/app/vendor/bundle/ruby/2.3.0/gems/curb-0.9.3/lib/curl.rb:22:in `get'
/app/lib/tasks/redmine.rake:307:in `block (4 levels) in <top (required)>'

以下是我在评论中提到的救援方法的总体思路:

loop do
  begin
    resp = Curl.get("http://someurl.com/users.json") do |http|
        http.headers["API-Key"] = ENV["API_KEY"]
    end
    # process successful response here
  rescue Curl::Err::TimeoutError
      # process error here
  end
end

然后您需要修改它以进行重试。这是 1 个实现(尽管未测试):

# Returns the response on success, nil on TimeoutError
def get1(url)
  begin
    Curl.get(url) do |http|
      http.headers["API-Key"] = ENV["API_KEY"]
    end
  rescue Curl::Err::TimeoutError
    nil
  end
end


# Returns the response on success, nil on TimeoutErrors after all retry_count attempts.
def get_with_retries(url, retry_count)
  retry_count.times do
    result = get1(url)
    return result if result
  end
  nil
end


response = get_with_retries("http://someurl.com/users.json", 3)
if response
  # handle success
else
  # handle timeout failure
end

我们也可以分块做

def handle_timeouts
   begin
     yield
   rescue Curl::Err::TimeoutError
     retry
   end
end

handle_timeouts do
  resp = Curl.get("http://someurl.com/users.json") do |http|
    http.headers["API-Key"] = ENV["API_KEY"]
  end
end