传递带有自定义异常的对象的正确方法是什么?我很确定这段代码是用来工作的,但是现在它抛出了一个错误。在
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'
只是另一种类型的对象:
这将使响应可用作
.text
异常的引发和捕获是正确的,这里的问题是您期望异常具有不存在的
text
属性。从内置异常类型继承时,可以使用args
属性,该属性将是异常参数的元组,例如:在本例中,您可以使用}。如果异常只有一个参数,那么
str(r)
,而不是{str(r)
将等价于str(r.args[0])
,否则它将等价于str(r.args)
。在如果要将
^{pr2}$text
属性添加到FailedPostException
,可以执行以下操作:请注意,在python3.x中,您只需使用
super().__init__(text, *args)
。在您可以保留对原始
Response
对象的引用并公开其属性,如下所示:以防您需要反省
^{pr2}$Response
对象的更多内容相关问题 更多 >
编程相关推荐