8

Im trying to handle errors with Python-Twitter, for example: when I do the below passing a Twitter account that returns a 404 I get the following response...

import twitter

# API connection
api = twitter.Api(consumer_key='...',
              consumer_secret='...',
              access_token_key='...',
              access_token_secret='...')



try:
    data = api.GetUser(screen_name='repcorrinebrown')
Except Exception as err:
    print(err)

Response:

twitter.error.TwitterError: [{'code': 50, 'message': 'User not found.'}]

how can I iterate through this list on Except

2 Answers2

9

The message property of the exception object should hold the data you are looking for. Try this:

import twitter

# API connection
api = twitter.Api(consumer_key='...',
              consumer_secret='...',
              access_token_key='...',
              access_token_secret='...')



try:
    data = api.GetUser(screen_name='repcorrinebrown')
except Exception as err:
    print(err.message)
    for i in err.message:
        print(i)

However, you may want to except the specific exception rather than all exceptions:

except twitter.error.TwitterError as err:
    ...
elethan
  • 16,408
  • 8
  • 64
  • 87
0

For a more specific exception, I would use twitter.TweepError like this

try:
    user = api.get_user('user_handle')

except twitter.TweepError as error: #Speficically twitter errors
    print(error) 
Anjayluh
  • 1,647
  • 1
  • 13
  • 22