Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the error code from tweepy exception instance

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.

like image 494
José D. Avatar asked Jun 17 '13 22:06

José D.


People also ask

What is Wait_on_rate_limit?

wait_on_rate_limit – Whether or not to automatically wait for rate limits to replenish. wait_on_rate_limit_notify – Whether or not to print a notification when Tweepy is waiting for rate limits to replenish.

What does Tweepy return?

Returns full Tweet objects for up to 100 Tweets per request, specified by the id parameter.

Is Tweepy deprecated?

Deprecated since version 4.10: The Twitter API v1. 1 endpoint this method uses is now deprecated and will be retired on October 29, 2022.


3 Answers

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

like image 117
Jeyekomon Avatar answered Oct 02 '22 21:10

Jeyekomon


How about this?

except tweepy.TweepError as e:
    print e.message[0]['code']  # prints 34
    print e.args[0][0]['code']  # prints 34
like image 30
alecxe Avatar answered Oct 02 '22 20:10

alecxe


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

like image 40
dzz Avatar answered Oct 02 '22 20:10

dzz