How to catch error Connection reset by peer (Errno::ECONNRESET)

14,769

Solution 1

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

Solution 2

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
Share:
14,769

Related videos on Youtube

revolver
Author by

revolver

Updated on June 27, 2022

Comments

  • revolver
    revolver over 1 year

    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)
    
  • Sean Moubry
    Sean Moubry about 8 years
    Or the more popular and maintained retriable gem.
  • Sean Moubry
    Sean Moubry about 8 years
    More information about this Ruby retry pattern: blog.mirthlab.com/2012/05/25/…