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

标签 python python-2.7 twitter tweepy

我是 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 但没有成功,我不知道该尝试什么。

最佳答案

从基异常类派生的每个行为良好的异常 has一个 args 属性(属于 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出于某种原因,即使它们是公共(public) API 的一部分。

因此您也可以使用此代码获取错误代码(类型 int):

e.api_code


历史:

以前使用 e.message[0]['code'] 访问错误代码,但现在不再有效。 message 属性为 deprecated in Python 2.6并在 Python 3.0 中删除。目前你得到一个错误 'TweepError' object has no attribute 'message'

关于python - 从 tweepy 异常实例中获取错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17157753/

相关文章:

php - fatal error : Call to undefined function add_action()

python - Python 3.7 数据类中的类继承

python - 通过命令行python批量上传视频到youtube

python - 如何通过使用easygui选择测试来依次运行python脚本?

python-2.7 - pyqtgraph删除pyqt4 gui中的持久图例

python - 如何将这种类型的数据 <hdf5 object reference> 转换为在 python 中更具可读性的内容?

Python: "re.match(pattern)"与 "re.search(' ^' + pattern)"之间的差异

python - 如何在 django-allauth 中禁用密码检查

android - 使用 Fabric SDK 获取 Twitter 用户电子邮件

ios - TWTRLogInButton(推特登录按钮)设置标题导致文字重叠