pythonerror-handlingpython-twitter

Python twitter package : get error code


I'm not yet very familiar with error handling in Python. I'd like to know how to retrieve the error code when I get an error using the python-twitter package :

import twitter

#[...]

try:
    twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
except twitter.TwitterHTTPError as twittererror:
     print(twittererror)

Twitter sent status 403 for URL: 1.1/friendships/create.json using parameters: (follow=True&oauth_consumer_key=XXX&oauth_nonce=XXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=XXX&oauth_token=XXX&oauth_version=1.0&screen_name=someone_who_blocked_me&oauth_signature=XXX) details: {'errors': [{'message': 'You have been blocked from following this account at the request of the user.', 'code': 162}]}

In this case, I'd like to retrieve the 'code': 162 part, or just the 162.

twittererror.args is a tuple with one element in it, which is a string, print(twittererror.args[0][0:10]) outputs Twitter se

How can I get the 162 ?

(Obviously, twittererror.args[0][582:585] is not the answer I'm looking for, as any other error message will be of a different length and the error code won't be at [582:585])


Solution

  • Looking at how the TwitterHTTPError is defined in this GitHub repo, you should obtain the dict with twittererror.response_data.

    Therefore you can do something like that:

    import twitter
    
    #[...]
    
    try:
        twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
    except twitter.TwitterHTTPError as twittererror:
         for error in twittererror.response_data.get("errors", []):
              print(error.get("code", None))