Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I "ignore" this ConnectionError using a try/except block?

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?

like image 332
david Avatar asked Mar 07 '23 02:03

david


2 Answers

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.

like image 64
Matti Lyra Avatar answered Apr 08 '23 08:04

Matti Lyra


Try catching requests connectionError (and not the one that is a subClass of OSError).

So instead of except ConnectionError: do except requests.exceptions.ConnectionError:

like image 40
kerbelp Avatar answered Apr 08 '23 09:04

kerbelp