Checking for Timeout Error in python
52,980
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)
Author by
diplosaurus
Updated on July 09, 2022Comments
-
diplosaurus almost 2 years
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 addingfrom exceptions import *
but with no luck. I've also tried importingOSError
because the docs sayTimeoutError
is a subclass, but I was unable to accessTimeoutError
after importingOSError
.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
-
Martijn Pieters almost 10 yearsPro tip: use httpbin.org to demonstrate specific response behaviour. There is a
http://httpbin.org/delay
route that'll respond after a configurable delay.