RubyCurb(libcurl):测试GET请求中的超时



使用curb宝石(https://github.com/taf2/curb)从REST API发送到CCD_ 2。

  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

无法找到/弄清楚如何测试超时结果。

我错过了什么?

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

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

然后,您需要对此进行修改才能重试。这里有一个实现(未测试):

# 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

相关内容

  • 没有找到相关文章

最新更新