Checking for Timeout Error in python

2020-02-29 01:11发布

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

1条回答
你好瞎i
2楼-- · 2020-02-29 01:41

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)
查看更多
登录 后发表回答