user5674825
user5674825

Reputation:

python-twitter exception handling

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

Upvotes: 8

Views: 2266

Answers (2)

Anjayluh
Anjayluh

Reputation: 1786

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) 

Upvotes: 0

elethan
elethan

Reputation: 16993

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:
    ...

Upvotes: 9

Related Questions