revolver
revolver

Reputation: 2405

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

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)

Upvotes: 17

Views: 15491

Answers (2)

Daniel Pittman
Daniel Pittman

Reputation: 17212

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

Upvotes: 40

Ben Jackson
Ben Jackson

Reputation: 860

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

Upvotes: 5

Related Questions