检查python中的超时错误
因此,在请求之后,我有一个非常通用的日志语句:检查python中的超时错误,python,python-2.7,exception,python-requests,Python,Python 2.7,Exception,Python Requests,因此,在请求之后,我有一个非常通用的日志语句: try: r = requests.get(testUrl, timeout=10.0) except Exception, err: logger.error({"message": err.message}) 除了TimeoutError之外,这对我抛出的所有东西都非常有效。当请求超时时,我返回的错误是一个元组,它尝试序列化但失败 我的问题是如何捕捉这一类错误?对于初学者来说,TimeoutError不是我能接触到的东西。我尝
try:
r = requests.get(testUrl, timeout=10.0)
except Exception, err:
logger.error({"message": err.message})
除了TimeoutError
之外,这对我抛出的所有东西都非常有效。当请求超时时,我返回的错误是一个元组,它尝试序列化但失败
我的问题是如何捕捉这一类错误?对于初学者来说,
TimeoutError
不是我能接触到的东西。我尝试从异常导入添加*
,但没有成功。我还尝试导入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可以处理异常:
try:
r = requests.get(testUrl, timeout=10.0)
except requests.Timeout as err:
logger.error({"message": err.message})
except requests.RequestException as err:
# handle other errors
例如:
>>> import requests
>>> url = "http://httpbin.org/delay/2"
>>> try:
... r = requests.get(url, timeout=1)
... except requests.Timeout as err:
... print(err.message)
...
HTTPConnectionPool(host='httpbin.org', port=80): Read timed out. (read timeout=1)
TimeoutError
是由提供的自定义异常。@MartijnPieters啊,我以为它就是这里提到的一个:当有疑问时,打印异常的\uuuuuu模块\uuuuu
属性。我是从concurrent.futures
来这里的TimeoutError
,它只是并发的.futures.TimeoutError
。它是Python3中的公告,但不是Python2中的公告。Pro提示:用于演示特定的响应行为。有一个http://httpbin.org/delay
可配置延迟后响应的路由。