19

I'm new to python and I'm trying to use a library. It raises an exception, and I am trying to identify which one. This is what I am trying:

except tweepy.TweepError as e:
    print e
    print type(e)
    print e.__dict__
    print e.reason
    print type(e.reason)

This is what I am getting:

[{u'message': u'Sorry, that page does not exist', u'code': 34}]
<class 'tweepy.error.TweepError'>
{'reason': u"[{u'message': u'Sorry, that page does not exist', u'code': 34}]", 'response': <httplib.HTTPResponse instance at 0x00000000029CEAC8>}
[{u'message': u'Sorry, that page does not exist', u'code': 34}]
<type 'unicode'>

Im trying to get to that code. I have tried e.reason.code with no success and I have no idea what to try.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
José D.
  • 4,175
  • 7
  • 28
  • 47
  • Yeah - I might have misread that one - What about `e.reason[0]['code']` ? – Jon Clements Jun 17 '13 at 22:28
  • Traceback (most recent call last): File "descargar.py", line 70, in print e.reason[0]['code'] TypeError: string indices must be integers – José D. Jun 17 '13 at 22:28
  • @alecxe Sorry, this was some time ago, I don't remember what I did, but i did get the code (as I wanted). Nevertheless, your answer works, so I have accept it :) – José D. May 05 '14 at 07:56

6 Answers6

24

Every well-behaved exception derived from the base Exception class has an args attribute (of type tuple) that contains arguments passed to that exception. Most of the time only one argument is passed to an exception and can be accessed using args[0].

The argument Tweepy passes to its exceptions has a structure of type List[dict]. You can get the error code (type int) and the error message (type str) from the argument using this code:

e.args[0][0]['code']
e.args[0][0]['message']

The TweepError exception class also provides several additional helpful attributes api_code, reason and response. They are not documented for some reason even though they are a part of public API.

So you can get the error code (type int) also using this code:

e.api_code


History:

The error code used to be accessed using e.message[0]['code'] which no longer works. The message attribute has been deprecated in Python 2.6 and removed in Python 3.0. Currently you get an error 'TweepError' object has no attribute 'message'.

Jeyekomon
  • 2,878
  • 2
  • 27
  • 37
  • 1
    Thank you for this. I was going crazy lol The docs are really outdated – Sergio La Rosa Mar 06 '18 at 09:53
  • 2
    `e.api_code` returns `None`. At least when `status code = 401`, maybe it's a bug. – j4n7 Mar 27 '18 at 10:46
  • @j4n7 Look at the [Twitter API documentation](https://developer.twitter.com/en/docs/basics/response-codes). If I understand it right, every response contains a HTTP status code but not every response contains an Error code (API code). API codes are provided only for the most common errors. – Jeyekomon Mar 27 '18 at 12:33
  • 1
    Weirdly enough. Rate limit is not in `e.api_code`. Use the `tweepy.RateLimit` exception. or the `e.args[0][0]['code']` – salvob Jun 19 '18 at 14:22
  • How is this not marked as the best answer!! Thank you. – viral gandhi Nov 20 '18 at 08:28
21

How about this?

except tweepy.TweepError as e:
    print e.message[0]['code']  # prints 34
    print e.args[0][0]['code']  # prints 34
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    It seems to me that since `e` is a list object, that `e.message[0]['code']` wouldn't work. Wouldn't you instead use `e[0]['code']`? – Austin A Jan 06 '15 at 04:56
  • Actually, now that I look at the github page, tweepError is overriding the print statement with the `__str__` so that may be why I've been having issues. Do you happen to know how `e` is structured? – Austin A Jan 06 '15 at 06:33
  • e.message is not working anymore. Please check @Jeyekomon answer – hamza saber Jan 17 '21 at 16:46
9

Things have changed quite a bit since 2013. The correct answer as of now is to use e.api_code.

dzz
  • 327
  • 3
  • 12
2

To get just the error code use the method monq posted. The following example illustrates how to get both the error code and the message. I had to extract the message from the e.reason string, if anyone has a better method to retrieve just the message, please share.

Note: This code should work for any error code/reason with the following format.

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

def getExceptionMessage(msg):
    words = msg.split(' ')

    errorMsg = ""
    for index, word in enumerate(words):
        if index not in [0,1,2]:
            errorMsg = errorMsg + ' ' + word
    errorMsg = errorMsg.rstrip("\'}]")
    errorMsg = errorMsg.lstrip(" \'")

    return errorMsg

And you can call it like so:

try:
    # Some tweepy api call, ex) api.get_user(screen_name = usrScreenName)
except tweepy.TweepError as e:
    print (e.api_code)
    print (getExceptionMessage(e.reason))
DowntownDev
  • 842
  • 10
  • 15
1

As of December 2021 (tweepy v4.4.0) the correct way is:

except tweepy.TweepyException as e:
    print(e)

source: https://docs.tweepy.org/en/v4.4.0/changelog.html?highlight=TweepError#new-features-improvements

stevx
  • 11
  • 1
0

Here is how I do it:

except tweepy.TweepError as e:
    print e.response.status
tmatti
  • 101
  • 1
  • 5