10

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

5
  • TimeoutError is a custom exception provided by the requests package. Commented Jun 13, 2014 at 17:28
  • 2
    @MartijnPieters Ahh, I thought it was the one referred to here: docs.python.org/3/library/exceptions.html#TimeoutError Commented Jun 13, 2014 at 18:08
  • 3
    When in doubt, print the .__module__ attribute of an exception. Commented Jun 13, 2014 at 18:08
  • 3
    I came here for TimeoutError from concurrent.futures, which is just concurrent.futures.TimeoutError. Commented Dec 12, 2017 at 22:52
  • 1
    It is a bulletin in Python 3, but not in Python 2. Commented Mar 16, 2018 at 9:01

1 Answer 1

22

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Pro tip: use httpbin.org to demonstrate specific response behaviour. There is a http://httpbin.org/delay route that'll respond after a configurable delay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.