传递带异常的对象

2024-10-01 13:46:02 发布

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

传递带有自定义异常的对象的正确方法是什么?我很确定这段代码是用来工作的,但是现在它抛出了一个错误。在

class FailedPostException(Exception):
    pass

def post_request(request):
    session = requests.Session()
    response = session.send(request.prepare(), timeout=5, verify=True)

    if response.status_code is not requests.codes.ok:
        raise FailedPostException(response)

    session.close()
    return response

try:
    ...
except FailedPostException as r:
    // type(r) - Requests.Response
    print r.text

AttributeError: 'FailedPostException' object has no attribute 'text'

Tags: 对象方法代码textresponserequestsessiondef
3条回答

只是另一种类型的对象:

class FailedPostException(Exception):
    def __init__(self, text):
        Exception.__init__(self, text)
        self.text = text

这将使响应可用作.text

异常的引发和捕获是正确的,这里的问题是您期望异常具有不存在的text属性。从内置异常类型继承时,可以使用args属性,该属性将是异常参数的元组,例如:

try:
    ...
except FailedPostException as r:
    print r.args[0]

在本例中,您可以使用str(r),而不是{}。如果异常只有一个参数,那么str(r)将等价于str(r.args[0]),否则它将等价于str(r.args)。在

如果要将text属性添加到FailedPostException,可以执行以下操作:

^{pr2}$

请注意,在python3.x中,您只需使用super().__init__(text, *args)。在

您可以保留对原始Response对象的引用并公开其属性,如下所示:

class FailedPostException(Exception):
    def __init__(self, rsp):
        super(FailedPostException, self).__init__()
        self.response = rsp
    @property
    def text(self):
        return self.response.text
    @property
    def status_code(self):
        return self.response.status_code
    #other properties if interested....

以防您需要反省Response对象的更多内容

^{pr2}$

相关问题 更多 >