在python中检查超时错误

2024-04-25 19:36:46 发布

您现在位置:Python中文网/ 问答频道 /正文

所以在请求之后我有一个非常通用的日志记录语句:

try:
    r = requests.get(testUrl, timeout=10.0)
except Exception, err:
    logger.error({"message": err.message})

除了TimeoutError之外,这对我所投入的一切都很有用。当请求超时时,返回的err是一个元组,它尝试并未能序列化。

我的问题是怎样才能抓住这一类错误?对于初学者来说,TimeoutError不是我能接触到的东西。我试过添加from exceptions import *,但没有成功。我也尝试过导入OSError,因为文档中说TimeoutError是一个子类,但是导入OSError之后我无法访问TimeoutError

TimeoutError docs

我计划按以下顺序列出我的例外情况:

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


Tags: message记录exceptionerror语句allerrhandle
1条回答
网友
1楼 · 发布于 2024-04-25 19:36:46

您可以处理^{}异常:

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)

相关问题 更多 >