从tweepy异常实例获取错误代码

2024-04-29 06:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我正在尝试使用一个库。它引发了一个例外,我正试图确定是哪一个。这就是我正在尝试的:

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

这就是我得到的:

[{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'>

我试着去查那个密码。我尝试了e.reason.code,但没有成功,我不知道该尝试什么。


Tags: messagethattypepagenotcodeexistreason
3条回答

这个怎么样?

except tweepy.TweepError as e:
    print e.message[0]['code']  # prints 34
    print e.args[0][0]['code']  # prints 34

自2013年以来,情况发生了很大变化。现在正确的答案是使用e.api_code

从包含传递给该异常的参数的基异常类hasargs属性(类型为tuple)派生的每个行为良好的异常。大多数情况下,只有一个参数传递给异常,可以使用args[0]访问。

Tweepy传递给其异常的参数具有类型为List[dict]的结构。可以使用以下代码从参数获取错误代码(类型int)和错误消息(类型str):

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

TweepError exception class还提供了几个附加的有用属性api_codereasonresponse。它们之所以是not documented是因为某些原因,即使它们是公共API的一部分。

因此,还可以使用以下代码获取错误代码(类型int):

e.api_code


历史记录:

以前使用e.message[0]['code']访问的错误代码不再工作。在Python 3.0中,message属性已被deprecated in Python 2.6删除。当前出现错误'TweepError' object has no attribute 'message'

相关问题 更多 >