2015-05-13 19 views
0

我試圖創建一個rescue,如果和當有一個Twitter::Error::NotFound錯誤(如不存在),它將繼續通過循環。請幫忙,謝謝。在Ruby中,你可以創建一個twitter的救援,當有錯誤時它會繼續循環?

下面是代碼,

begin 
    File.open("user_ids.txt") do |file| 
    file.each do |id| 
     puts client.user("#{id}").screen_name 
    rescue Twitter::Error::NotFound => error 
     next # skip this item 
    end 
    end 
end 

取而代之的是retry方法是有一個可以跳過,並保持在循環移動到下一個項目的方法? 我很確定error.rate_limit不適用(我從另一個救援呼叫複製此代碼),是否有另一種方法調用?像error.notfound.continue_with_loop

我想創造一個救援,如果和當有一個錯誤,如does not exist,所以它會繼續通過循環。請幫忙,謝謝。

+0

yes'next'將繼續並重試循環中的下一項。重試'將重試循環與相同的項目 –

+0

啊okie doke,謝謝@TarynEast – marriedjane875

回答

0

yes next將繼續並重試循環中的下一個項目。 retry將使用相同的項目重試循環。

注意:對於該方法中的所有do,您沒有足夠的end s。所以我想嘗試:

begin 
    File.open("user_ids.txt") do |file| 
    file.each do |id| 
     puts client.user("#{id}").screen_name 
    rescue Twitter::Error::NotFound => error 
     sleep error.rate_limit.reset_in + 1 
     next # skip this item 
    end 
    end 
end 

注:參見縮進如何正確清楚,當你缺少一個end

您可能需要將當前周圍的開始/結束塊 - 僅僅圍繞您想要解救的代碼 - 從(或者它會默認爲外部開始/結束而不是您的循環)

File.open("user_ids.txt") do |file| 
    file.each do |id| 
    begin 
     puts client.user("#{id}").screen_name 
    rescue Twitter::Error::NotFound => error 
     sleep error.rate_limit.reset_in + 1 
     next # skip this item 
    end 
    end 
end 
+0

我得到一個錯誤,仍然說'twitter.rb:297:語法錯誤,意想不到的keyword_rescue,期待keyword_end 救援Twitter的:錯誤: :NOTFOUND =>錯誤 ^ twitter.rb:297:語法錯誤,意想不到=> 救援的Twitter ::錯誤:: NOTFOUND =>錯誤 ^」 – marriedjane875

+0

我修改了上面的代碼看它究竟是如何看起來崇高 – marriedjane875

+0

整潔,謝謝 - 它也可以幫助你在這裏做這件事,所以我們可以很容易地看到結構,並告訴是否有什麼缺失.... :) –