如何捕获错误通过对等方重置连接(Errno :: ECONNRESET)

时间:2012-02-09 03:15:08

标签: ruby

以下代码有时会生成“按对等方重置连接”错误。谁能告诉我如何处理这个异常?

doc = Nokogiri::HTML(open(url))
Connection reset by peer (Errno::ECONNRESET)

2 个答案:

答案 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