我正在使用 Rails 4.2.3 和 Nokogiri 从网站获取数据。当我没有从服务器得到任何响应时,我想执行一个操作,所以我有:
begin
content = open(url).read
if content.lstrip[0] == '<'
doc = Nokogiri::HTML(content)
else
begin
json = JSON.parse(content)
rescue JSON::ParserError => e
content
end
end
rescue Net::OpenTimeout => e
attempts = attempts + 1
if attempts <= max_attempts
sleep(3)
retry
end
end
请注意,这与从服务器获取 500 不同。我只想在完全没有响应时重试,要么是因为我没有 TCP 连接,要么是因为服务器无法响应(或其他一些导致我没有得到任何响应的原因)。除了我如何处理这种情况之外,还有更通用的方法来考虑这种情况吗?我觉得还有很多其他我没有想到的异常类型。