I have a python function that may raise an exception. The caller catches the exception and deals with it. Now I would like to add a decorator to that function that also<
I just wrote a class similar to what you are doing, but with a little more options available. Here it is:
class ErrorIgnore(object):
def __init__(self, errors, errorreturn = None, errorcall = None):
self.errors = errors
self.errorreturn = errorreturn
self.errorcall = errorcall
def __call__(self, function):
def returnfunction(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as E:
if type(E) not in self.errors:
raise E
if self.errorcall is not None:
self.errorcall(E, *args, **kwargs)
return self.errorreturn
return returnfunction
Common usage would be something like:
def errorcall(E, *args):
print 'exception skipped', E
@ErrorIgnore(errors = [ZeroDivisionError, ValueError], errorreturn = None, errorcall = errorcall)
def myfunction(stuff):
# do stuff
# return stuff
# the errors shown are skipped
Just use raise;
(i.e. do not raise anything specific, just raise;
) in a catch
block to re-raise the exception without "resetting" the traceback.