2012-02-09 78 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

相關問題