我是 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_code
、reason
和 response
。他们是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/