【问题标题】:Checking for Timeout Error in python在python中检查超时错误
【发布时间】:2014-08-04 08:04:07
【问题描述】:

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

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

【问题讨论】:

  • TimeoutErrorthe requests package 提供的自定义异常。
  • @MartijnPieters 啊,我还以为是这里提到的那个:docs.python.org/3/library/exceptions.html#TimeoutError
  • 如有疑问,请打印异常的.__module__ 属性。
  • 我来这里是为了TimeoutError 来自concurrent.futures,也就是concurrent.futures.TimeoutError
  • 这是 Python 3 中的公告,但不是 Python 2。

标签: python python-2.7 exception python-requests


【解决方案1】:

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

【讨论】:

  • 专业提示:使用httpbin.org 来演示特定的响应行为。有一个 http://httpbin.org/delay 路由会在可配置的延迟后响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多