Reputation: 2405
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
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
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