Search code examples
rubytwitter-bootstraploopstwitterrescue

In Ruby, can you create a rescue for twitter for when there is an error it will continue the loop?


I'm trying to create a rescue that if and when there is an Twitter::Error::NotFound error (such as does not exist) it will just keep going through the loop. Please help, thanks.

Below is the code,

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

Instead of the retry method is there a a method that can skip and keep moving on to the next item in the loop? I'm pretty sure the error.rate_limit does not apply (I copied this code from a different rescue call), is there another method to call? like error.notfound.continue_with_loop

I would like to create a rescue that if and when there is an error such as does not exist so it will just keep going through the loop. Please help, thanks.


Solution

  • yes next will continue and retry the next item in a loop. retry will retry the loop with the same item.

    Note: you don't have enough ends for all the do that are in that method. So I'd try:

    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
    

    Note: see how proper indentation makes it clear when you're missing an end ?

    You may need to shift the begin/end block that is currently around the lot - to just be around the code that you want to rescue-from (or it'll default to the outside begin/end rather than your loop)

    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