检查python中的超时错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24210792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking for Timeout Error in python
提问by diplosaurus
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})
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. 当请求超时时,我返回的 err 是一个它尝试但未能序列化的元组。
My question is how do I catch just this one type of error? For starters TimeoutErroris not something I have access to. I have tried adding from exceptions import *but with no luck. I've also tried importing OSErrorbecause the docs say TimeoutErroris a subclass, but I was unable to access TimeoutErrorafter importing OSError.
我的问题是如何仅捕获这种类型的错误?对于初学者来说,TimeoutError我无法访问。我尝试添加from exceptions import *但没有运气。我也尝试过导入,OSError因为文档说TimeoutError是一个子类,但是TimeoutError导入OSError.
I plan to either list my exceptions in order:
我计划按顺序列出我的例外情况:
except TimeoutError, err:
#handle this specific error
except Exception, err:
#handle all other errors
or just check for type:
或者只是检查类型:
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
采纳答案by alecxe
You can handle requests.Timeoutexception:
您可以处理requests.Timeout异常:
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
Example:
例子:
>>> 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)

