Search code examples
rubytwitterrescue

Twitter Gem - rescue's to consider?


I'm working with the Twitter Gem and I've created a long running ruby task. I would like it to be able to handle common errors so I'm looking to build a list of those I should consider to protect against (for example the fail whale 500)

Here is the begin/end loop my code functions in:

Begin

# My (omitted) very long ruby task
# filled with Twitter API requests

rescue Errno::ENOENT
  sleep(5)
  logger.info "ENOENT error - attempting to retry"
  retry
rescue Errno::ETIMEDOUT
  sleep(5)
  logger.info " Operation timed out - attempting to retry"
  retry
rescue Errno::ECONNRESET
  sleep(5)
  logger.info "Connection reset by peer - attempting to retry"
  retry
end 

Can you think of any other Errors to protect and retry against? Is this a well structured way to handle errors? What are some design implementations I should consider?


Solution

  • Consider having a catch-all exception handler at the end that logs what kind of exception was encountered and re-raises it. Your script may fail the first time, but at least you'll find out why.

    begin
    
    # My (omitted) very long ruby task
    # filled with Twitter API requests
    
    rescue Errno::ENOENT
      sleep(5)
      logger.info "ENOENT error - attempting to retry"
      retry
    rescue Errno::ETIMEDOUT
      sleep(5)
      logger.info " Operation timed out - attempting to retry"
      retry
    rescue Errno::ECONNRESET
      sleep(5)
      logger.info "Connection reset by peer - attempting to retry"
      retry
    rescue # This rescues StandardError and its children
      sleep(5)
      # The next line is somewhat pseudocode, because I don't use logger
      logger.this_is_somewhat_bad "Somewhat bad exception #{$!.class} #{$!} happened - I'm giving up"
      raise
    rescue Exception
      sleep(5)
      # The next line is somewhat pseudocode, because I don't use logger
      logger.omg_wtf_bbq "Really bad exception #{$!.class} #{$!} happened - I'm giving up"
      raise
    end