Sam*_*Sam 6 ruby ruby-on-rails httparty ruby-on-rails-3.2
我正在使用httparty(0.13.1)gem.我正在使用httparty进行一系列API调用.我的一些初始API调用成功,但后来的调用连续失败.我添加了180秒的超时.我搜索谷歌但我找不到任何解决方案.很长一段时间我因此而苦苦挣扎.
我的代码:
response = HTTParty.get("http://pubapi.cryptsy.com/api.php?method=marketdatav2", timeout: 180)
Run Code Online (Sandbox Code Playgroud)
错误:
A Net::ReadTimeout occurred in background at 2014-10-05 11:42:06 UTC :
Run Code Online (Sandbox Code Playgroud)
我不知道这次是否有效?我觉得180秒足以检索响应,因为默认超时是60秒.如果我想处理网络读取超时错误,有没有办法做到这一点?如果发生此错误,我想返回nil.或者是否有最佳解决方案可以避免发生此错误?
cjs*_*eon 15
有一个不同模块的类似问题,在我的情况下,如果重试它可能会成功,所以我抓住超时并重试.
max_retries = 3
times_retried = 0
begin
#thing that errors sometimes
rescue Net::ReadTimeout => error
if times_retried < max_retries
times_retried += 1
puts "Failed to <do the thing>, retry #{times_retried}/#{max_retries}"
retry
else
puts "Exiting script. <explanation of why this is unlikely to recover>"
exit(1)
end
end
Run Code Online (Sandbox Code Playgroud)
留在这里以防其他人觉得它有用.
您可以rescue用来处理超时异常:
begin
HTTParty.get("http://pubapi.cryptsy.com/api.php?method=marketdatav2", timeout: 180)
rescue Net::ReadTimeout
nil
end
Run Code Online (Sandbox Code Playgroud)