1

I have created the following decorator looking at some online resources:

import logging

def exception_handler(func):

    def inner_function(*args, **kwargs):

        try:

            output=func(*args, **kwargs)
            
            return output

        except Exception:

            logging.error('Error in "{}" function'.format(func.__name__))

    return inner_function

This decorator applied to every function tries to execute it otherwise it writes to a log file.

Example of use:

@exception_handler
def sum_2_numbers(x,y):
    return x+y

sum_2_numbers(3,'a')

Is it also possible to allow some action to be executed after the exception, depending on the function to which it is applied?

I mean I want to add some istructions if the exception is rised. (for example a rollback after the exception).

Any help?

mat
  • 181
  • 14
  • Does adding `rollback` in the exception-handler right after `logging.error(...)` suffice? Or do you want to add an argument to the decorator, then see https://stackoverflow.com/q/5929107/42580 – UlfR Sep 29 '22 at 10:46
  • I want to add statements after the exception, for example if the exception arises, do statement1 (perform an operation), statement2 (calculate a value) and close. – mat Sep 29 '22 at 11:01

0 Answers0