【发布时间】:2014-08-04 08:04:07
【问题描述】:
所以我在请求后有一个非常通用的日志记录语句:
try:
r = requests.get(testUrl, timeout=10.0)
except Exception, err:
logger.error({"message": err.message})
除了TimeoutError 之外,这对我抛出的所有内容都非常有用。当请求超时时,我返回的错误是它尝试序列化但未能序列化的元组。
我的问题是如何只捕获这一种类型的错误?对于初学者TimeoutError 不是我可以访问的。我试过添加from exceptions import *,但没有运气。我也尝试过导入OSError,因为文档说TimeoutError 是一个子类,但是在导入OSError 后我无法访问TimeoutError。
我打算按顺序列出我的例外情况:
except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
或者只检查类型:
except Exception, err:
if isinstance(err, TimeoutError):
#handle specific error
#handle all other errors
Python 2.7.3 和 Django 1.5
【问题讨论】:
-
TimeoutError是therequestspackage 提供的自定义异常。 -
@MartijnPieters 啊,我还以为是这里提到的那个:docs.python.org/3/library/exceptions.html#TimeoutError
-
如有疑问,请打印异常的
.__module__属性。 -
我来这里是为了
TimeoutError来自concurrent.futures,也就是concurrent.futures.TimeoutError。 -
这是 Python 3 中的公告,但不是 Python 2。
标签: python python-2.7 exception python-requests