19

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

4

6 回答 6

23

从基 Exception 类派生的每个表现良好的异常都有一个args属性(类型为tuple),其中包含传递给该异常的参数。大多数情况下,只有一个参数被传递给异常并且可以使用args[0].

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

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

TweepError异常类还提供了几个额外的有用属性api_codereason并且response. 尽管它们是公共 API 的一部分,但由于某种原因没有记录它们。

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

e.api_code


历史:

以前使用的错误代码e.message[0]['code']不再有效。该message属性在 Python 2.6 中已被弃用,并在 Python 3.0 中被删除。目前你得到一个错误'TweepError' object has no attribute 'message'

于 2018-01-29T10:42:07.713 回答
21

这个怎么样?

except tweepy.TweepError as e:
    print e.message[0]['code']  # prints 34
    print e.args[0][0]['code']  # prints 34
于 2013-06-18T12:16:40.740 回答
9

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

于 2016-09-14T20:59:21.533 回答
2

要仅获取错误代码,请使用方法 monq 发布。以下示例说明了如何获取错误代码和消息。我必须从 e.reason 字符串中提取消息,如果有人有更好的方法来检索消息,请分享。

注意:此代码适用于具有以下格式的任何错误代码/原因。

[{'code': 50, 'message': '找不到用户。'}]

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

你可以这样称呼它:

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))
于 2017-01-13T06:32:27.200 回答
0

这是我的做法:

except tweepy.TweepError as e:
    print e.response.status
于 2013-06-18T21:51:50.737 回答
0

截至 2021 年 12 月(tweepy v4.4.0),正确的方法是:

except tweepy.TweepyException as e:
    print(e)

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

于 2021-12-18T00:08:05.457 回答