问题描述
因此,在请求后,我有一个非常通用的日志记录语句:
So I have a pretty generic logging statement after a request:
try:
r = requests.get(testUrl, timeout=10.0)
except Exception, err:
logger.error({"message": err.message})
除了 TimeoutError
以外,它对我抛出的所有内容都非常有用。当请求超时时,我得到的是一个元组,它尝试并且无法序列化。
This works great for everything I've thrown at it except TimeoutError
. When the request times out the err I get back is a tuple that it tries and fails to serialize.
我的问题是如何只捕获这种错误?对于初学者来说,我无法访问 TimeoutError
。我试过从例外导入中添加 *
,但是没有运气。我也尝试导入 OSError
,因为文档说 TimeoutError
是一个子类,但是我无法访问<$导入 OSError
后c $ c> TimeoutError 。
My question is how do I catch just this one type of error? For starters TimeoutError
is not something I have access to. I have tried adding from exceptions import *
but with no luck. I've also tried importing OSError
because the docs say TimeoutError
is a subclass, but I was unable to access TimeoutError
after importing OSError
.
我打算依次列出我的例外情况:
I plan to either list my exceptions in order:
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
Python 2.7.3 & Django 1.5
推荐答案
您可以处理例外:
You can handle requests.Timeout
exception:
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)
这篇关于在python中检查超时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!