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
Connection errors can occur for a variety of reasons. For example, a failure in any of the internal connections described in How Connection Between the Application and DBMS Server Is Established results in a connection error. How connection errors are reported depends on where the failure occurs.
If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response. raise_for_status. That will raise an HTTPError, if the response was an http error. The exception list on the Request website isn't complete.
Just catch HTTPError , handle it, and if it's not Error 404, simply use raise to re-raise the exception. See the Python tutorial. can i do urllib2. urlopen("*") to handle any 404 errors and route them to my 404.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With