try-except is used with decorators

Preface

Laziness promotes invention. Every time I write code, I always use try except for every function. It’s really tiring, so why don’t I put a decorator on it.

This decorator must also meet several requirements:

  • There is no impact on the normal operation of the decorated function.
  • The decorated function runs incorrectly and does not affect the main program, and logs can be retained.
  • The decorator should set default return parameters, and the parameters should be adjusted according to the decorated function

code

No need to return default parameter decorator
def try_except2(func): 
  def handler(*args, **kwargs): 
    try: 
      func(*args, **kwargs) 
    except (BaseException,Exception) as e: 
      print(traceback.format_exc()) #Used to record errors Log 
      return "The return here replaces the a returned by error2" 
  return handler
@try_except2
def error2(x):
  a=x/0
  return a
a=error2(1)
print(a)

>>>ZeroDivisionError: division by zero

>>>The return here replaces the a returned by error2

Decorator that can specify default return parameters

To put it simply, if the function runs normally, it returns a, x, 0; if the function runs incorrectly, it can still return the three parameters "the", "is", and "error"  . And these three parameters can be specified. Of course, you can also add an additional parameter to pass the specified log information.

def try_except(*parames): 
  def wrap(func): 
    def handler(*args, **kwargs): 
      try: 
        func(*args, **kwargs) 
      except (BaseException,Exception) as e: 
        print(traceback.format_exc( )) 
        return parames #What is returned here are the three return values ​​of "the", "is", and "error" in the decoration parameters 
    return handler 

  return wrap
@try_except("the","is","error")
def error1(x):
    a=x/0
    return a ,x ,0
a,b,c=error1(3)
print(a,b,c)

>>>ZeroDivisionError: division by zero

>>>the is error 

Summarize

Perfect, no more worries about unexpected program errors

Guess you like

Origin blog.csdn.net/qq_55542491/article/details/132752924
Recommended