Within my django project I am making a call out to a pull in some data.
I have organized the code below so that if the get request fails, it is ignored and the rest of the function continues (please no lectures on if this is bad practice or not).
job_results=[]
try:
resp = requests.get(mongo_job_results)
for item in resp.json():
job_results.append(item)
except ConnectionError:
pass
I still get the following error:
Exception Type: ConnectionError
Exception Value:
('Connection aborted.', OSError(99, 'Cannot assign requested address'))
What am I missing here?
You're missing the joy of Python namespaces. The requests
library has its own class called requests.exceptions.ConnectionError
(http://docs.python-requests.org/en/master/api/#requests.ConnectionError). An instance of this class is raised by the get
call.
The ConnectionError
class you're code is referring to is the python built-in ConnectionError
(https://docs.python.org/3.4/library/exceptions.html#ConnectionError).
These two are not the same class, so the interpreter ends up not executing the except
block, as you're not capturing an instance of the class that was raised.
To fix this you either need to do from requests.exceptions import ConnectionError
which will override the reference to the built-in ConnectionError
for your module's namespace.
An alternative, and arguably cleaner, option would be to just catch requests.exceptions.ConnectionError
- that makes it clear which connection error class you're intending to capture.
Try catching requests
connectionError (and not the one that is a subClass of OSError).
So instead of
except ConnectionError:
do
except requests.exceptions.ConnectionError:
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