以下代码有时会生成“按对等方重置连接”错误。谁能告诉我如何处理这个异常?
doc = Nokogiri::HTML(open(url))
Connection reset by peer (Errno::ECONNRESET)
答案 0 :(得分:35)
要抓住它,就像其他任何例外一样:
begin
doc = Nokogiri::HTML(open(url))
rescue Errno::ECONNRESET => e
puts "we are handling it!"
end
更有用的模式是尝试几次,然后放弃:
count = 0
begin
doc = Nokogiri::HTML(open(url))
rescue Errno::ECONNRESET => e
count += 1
retry unless count > 10
puts "tried 10 times and couldn't get #{url}: #{e}
end
答案 1 :(得分:4)
更有用的模式是使用retries gem:
with_retries(:max_tries => 5, :rescue => [Errno::ECONNRESET], :max_sleep_seconds => 10) do
doc = Nokogiri::HTML(open(url))
end