简体   繁体   中英

How pass exception raised in decorator to function decorated?

I'd like that the function decorated can catch the exception raised by its decorator

def decorator(func):
   def _decorator(request, *args, **kwargs):
       if condition:
           return func(request, *args, **kwargs)
       else:
          """
          THIS EXCEPTION CAN'T BE CAUGHT FROM FUNCTION DECORATED
          """
          raise LimitReached 
return _decorator

How can I head on?

It can't be done. The decorated function is an inner scope and can't catch exceptions raised in the decorator outer scope. Think about the three steps involved in running the code.

(1) The decorator runs some code before the decorated function is called... the decorated function can't catch any exceptions there because it hasn't run yet.

(2) The decorator calls the decorated function... now the decorator can't raise an exception because it isn't running.

(3) the function returns and the decorator code runs again... the decorated function can't catch anything because its aleady completed execution.

(edit)

There is a solution to the problem. func knows that it should be catching some sort of exception. This same func could be written to have a parameter that tells it that it is in an error condition. I'm not sure this is the best solution (is a decorator even needed here?) but I could be convinced...

def func(p1, p2, kw1=None, errorstate=None):
    if errorstate:
        do_error_path()
        return

def decorator(func):
   def _decorator(request, *args, **kwargs):
       if condition:
           return func(request, *args, **kwargs)
       else:
          kwargs = kwargs.copy()
          kwargs['errorstate'] = LimitReached()
          return func(request, *args, **kwargs)
return _decorator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM