在Python中检查超时错误

10 投票
1 回答
86909 浏览
提问于 2025-04-18 09:42

我有一个很普通的日志记录语句,用来处理请求:

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

关于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

1 个回答

21

你可以处理 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

举个例子:

>>> 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)

撰写回答