I’m currently writing a wrapper class. I want to be able to log exceptions properly but allow calling methods to be aware of exceptions which occur. My class looks like this:
import logging
log = logging.getLogger('module')
class MyAPIWrapper(library.APIClass):
def __init__(self):
self.log = logging.getLogger('module.myapiwrapper')
def my_wrapper_method(self):
try:
response = self.call_api_method()
return response.someData
except APIException, e:
self.log.exception('Oh noes!')
raise e #Throw exception again so calling code knows it happened
I’m a bit dubious about catching and exception just to log it and then re-raising it so the calling code can do something about it. What’s the proper pattern here?
There is nothing wrong with catching to log. However, I’d recommend:
By just doing a bare
raiseyou preserve the full traceback info. It’s also more explicit to put code that will only happen if you don’t have an exception in theelseclause, and it’s clearer what line you’re catching an exception from.It would also be fine for the calling class to do the logging if it’s handling the error anyway, but that may not be convenient for your app.
Edit: The documentation for
try ... except ... else ... finallyis under compound statements.