本文介绍了检查python中的超时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

尝试:r = requests.get(testUrl, timeout=10.0)除了异常,错误:logger.error({"message": err.message})

除了TimeoutError 之外,这对我抛出的所有内容都非常有用.当请求超时时,我返回的 err 是一个元组,它尝试并未能序列化.

我的问题是如何仅捕获这种类型的错误?对于初学者来说,TimeoutError 不是我可以访问的.我尝试添加 from exceptions import * 但没有运气.我也试过导入 OSError 因为文档说 TimeoutError 是一个子类,但在导入 OSError 后我无法访问 TimeoutError.

超时错误文档

我打算按顺序列出我的例外情况:

除了超时错误,错误:#处理这个特定的错误除了异常,错误:#处理所有其他错误

或者只是检查类型:

除了异常,错误:如果 isinstance(err, TimeoutError):#处理特定错误#处理所有其他错误

Python 2.7.3 &Django 1.5

解决方案

你可以处理 requests.Timeout 异常:

尝试:r = requests.get(testUrl, timeout=10.0)除了 requests.Timeout 作为错误:logger.error({"message": err.message})除了 requests.RequestException 作为错误:# 处理其他错误

示例:

>>>进口请求>>>url = "http://httpbin.org/delay/2">>>尝试:... r = requests.get(url, timeout=1)... 除了 requests.Timeout 作为错误:...打印(错误消息)...HTTPConnectionPool(host='httpbin.org', port=80):读取超时.(读取超时=1)

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.

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.

TimeoutError docs

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

解决方案

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

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)

这篇关于检查python中的超时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 09:57