17

The following code sometimes generates a "connection reset by peer" error. Can anyone show me how to handle this exception?

doc = Nokogiri::HTML(open(url))
Connection reset by peer (Errno::ECONNRESET)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
revolver
  • 2,385
  • 5
  • 24
  • 40

2 Answers2

40

To catch it, do it just like any other exception:

begin
  doc = Nokogiri::HTML(open(url))
rescue Errno::ECONNRESET => e
  puts "we are handling it!"
end

A more useful pattern is to try a couple of times, then give up:

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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Daniel Pittman
  • 16,733
  • 4
  • 41
  • 34
  • 1
    More information about this Ruby `retry` pattern: http://blog.mirthlab.com/2012/05/25/cleanly-retrying-blocks-of-code-after-an-exception-in-ruby/ – Sean Moubry Oct 19 '15 at 19:23
5

An even more useful pattern is to use the retries gem:

with_retries(:max_tries => 5, :rescue => [Errno::ECONNRESET], :max_sleep_seconds => 10) do
  doc = Nokogiri::HTML(open(url))
end
Ben Jackson
  • 860
  • 8
  • 11