2012-02-09 159 views

回答

31

抓住它,这样做只是像任何其他异常:

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 
+2

谢谢。真的从stackoverflow中学到了很多:) – revolver 2012-02-09 03:25:24

+1

关于这个Ruby'retry'模式的更多信息:http://blog.mirthlab.com/2012/05/25/cleanly-retrying-blocks-of-code-after-an-exception -in-ruby/ – 2015-10-19 19:23:32

4

的更有用的模式是使用retries gem

with_retries(:max_tries => 5, :rescue => [Errno::ECONNRESET], :max_sleep_seconds => 10) do 
    doc = Nokogiri::HTML(open(url)) 
end 
+1

或者更受欢迎和维护的[retriable](https://github.com/kamui/retriable)宝石。 – 2015-10-19 19:22:10

相关问题