Search code examples
rubyerror-handlingtwitter-client

how can I handle "error" in communication to twitter.com? (ruby + twitter gem)


I have nice piece of code that works. I tried to tweet the same text and I my script ended because /lib/ruby/gems/1.8/gems/twitter-0.9.4/lib/twitter.rb:87:in 'raise_errors': (403): Forbidden - Status is a duplicate. (Twitter::General)

I know I cannot tweet the same text twice but I thought I will get the error inside the response variable.

How can I deal with the error? So my script will finish nicely not because of an error?

oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')

client = Twitter::Base.new(oauth)
response = client.update('Heeeyyyyoooo from Twitter Gem!')

Solution

  • You can wrap any ruby statement or block of statements in begin..rescue..end to catch errors - you might want to try this:

    begin
      oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
      oauth.authorize_from_access('access token', 'access secret')
    
      client = Twitter::Base.new(oauth)
      response = client.update('Heeeyyyyoooo from Twitter Gem!')
    rescue Twitter::General
      # Catch the error and do nothing
    end
    

    If you wanted to catch any error you can change the rescue line to just say rescue. You can read more about them on the ruby-doc website.