python - wrapping class method in try / except using decorator -


I have a general purpose function that sends information about the exception of application lock I use the exception_handler function in the way of classes I do The app log handler, which is passed by the exception_handler and which makes Jason String, is actually sent to the logfile. It all works well

  def exception_handler (enter, then expire = false):. Exc_type, exc_value, exc_tb = sys.exc_info () file name, line_num, FUNC_NAME, text = traceback.extract_tb (exc_tb) [-1] log.error ('{0} thrown from module: {1} line {2} (End_num, text). Dell (file name, line_num, FUNC_NAME, text) Finished: sys.exit ()  <3} ({4}). Format (exc_value, file name, FUNC_NAME, line_num, text) / pre> 

Thus I use it: (a hyper-simplified example)

  def __init __ (self): self.log = {A class that applies the application log Is} DEF demo (self, name): try: Except print (name) exception: exception_handler (inside I want to change the exception_handler to use as a decorator for many ways. I am using utility exception_handler class demo1 (commodity) import log, true)   

  @handle_exceptions def func1 (self, name) {some code that is wrapped in a try / leaving the decorative object}   

I have seen about decorators In many articles, but I have not yet thought of what I want to do. I have to pass the reference of the active log object and have to pass 0 or more logic to the wrapped function.

"itemprop =" text ">

Such a decorator will be:

  def handle_exceptions (f): def wrapper (* args, ** kw): try: return f (* arg, ** kw) except for exceptions: itself = args [0] exception_handler (self.log, is true) Return Cover   

This decorator just tried to call a wrapped function inside a suite. < p> This can only be applied to the methods, because it assumes that the first argument is self .

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -