inControl inControl -3 years ago 215
Python Question

Python continue on gaierror using the requests library

I'm using the requests library for python and I would like the code to continue whenever this

('Connection aborted.', gaierror(-2, 'Name or service not known'))
error occurs. For some reason my try catch is being ignored and the error causes the application to exit anyway.

My code:

try:
self.doSomething();
except requests.exceptions.ConnectionError as e:
self.logger.error("A connection error occured.");
self.logger.error(str(e) + "\n");
except Exception as e:
self.logger.error("An error occured.");
self.logger.error(str(e) + "\n");

Answer Source

If the error is a socket.gaierror, which is a subclass of OSError which is a subclass of Exception, then the except Exception clause should be executed.

Try/except is a powerful tool in Python, however, if not used carefully, it can easily hide errors. Sometimes the best approach is to remove the try/except and read the full traceback. Another approach that works pretty well is to log the full traceback, unfortunately for the Python newcomer, there are ubiquitous examples of this done wrong. To get the full traceback, you need to either remove the try/except, or use

import sys
import traceback

try:
    risky_call()
except Exception:
    print(''.join(traceback.format_exception(*sys.exc_info)))

Or, if you have a logger configured

try:
    risky_call()
except Exception:
    logging.exception('')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download