How do I catch an exception in a decorator but allow the caller to catch it as well?

前端 未结 2 947
一向
一向 2020-12-30 04:03

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<

相关标签:
2条回答
  • 2020-12-30 04:43

    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
    
    0 讨论(0)
  • 2020-12-30 05:05

    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.

    0 讨论(0)
提交回复
热议问题