42

I am using a webservice to retrieve some data but sometimes the url is not working and my site is not loading. Do you know how I can handle the following exception so there is no problem with the site in case the webservice is not working?

Django Version: 1.3.1 
Exception Type: ConnectionError
Exception Value: 
HTTPConnectionPool(host='test.com', port=8580): Max retries exceeded with url:

I used

try:
   r = requests.get("http://test.com", timeout=0.001)
except requests.exceptions.RequestException as e:    # This is the correct syntax
   print e
   sys.exit(1)

but nothing happens

2
  • 1
    I'm not sure but shouldn't it be except requests.exceptions.RequestException, e:? also you are saying you have ConnectionError as an exception but i don't see that you catch this specific exception... Commented Jan 28, 2014 at 13:51
  • well because I am new to python I found the answer from here : stackoverflow.com/questions/16511337/… Commented Jan 28, 2014 at 13:56

1 Answer 1

87

You should not exit your worker instance sys.exit(1) Furthermore you 're catching the wrong Error.

What you could do for for example is:

from requests.exceptions import ConnectionError
try:
   r = requests.get("http://example.com", timeout=0.001)
except ConnectionError as e:    # This is the correct syntax
   print e
   r = "No response"

In this case your program will continue, setting the value of r which usually saves the response to any default value

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry did not see that you are catching the wrong error: You re getting a ConnectionError, so you need to catch this one (see edited answer)
It works! thank you very much! But I used except requests.exceptions.ConnectionError as e:
ConnectionError is also the name of a built-in error type - how can this be a widely used package when they have such horrible naming practices? Neither str nor repr gives any indication that the class isn't the built-in one. It doesn't even inherit from the built-in ConnectionError, it inherits from OSError instead (which the real built-in one also does).

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.