python-twitter exception handling
Asked Answered
Y

2

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

Yelp answered 21/11, 2016 at 17:54 Comment(0)
G
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:
    ...
Goneness answered 21/11, 2016 at 18:27 Comment(0)
A
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) 
Art answered 17/6, 2021 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.