I am trying to create a error handling decorator in django and where the logging happens in the decorator in case of an exception and the exception is raised back to the decorated function which then sends an error http response.
But when I try do this, If I add a Except block in the decorated function after the exception from decorator is raised back, then only the except block of the decorated function is getting executed and the except block of the decorator is left unexecuted.
MyDecorator.py
def log_error(message):
def decorator(target_function):
@functools.wraps(target_function)
def wrapper(*args, **kwargs):
try:
return target_function(*args, **kwargs)
except Exception as e:
print('except block of the decorator')
exceptiontype, exc_obj, exc_tb = sys.exc_info()
filename = traceback.extract_tb(exc_tb)[-2][0]
linenumber = traceback.extract_tb(exc_tb)[-2][1]
mylogger(message=str(e),description='Related to Registration',fileName=filename,lineNumber=linenumber, exceptionType = type(e).__name__)
raise
return wrapper
return decorator
Decorated function
@log_error('message')
def action(self, serializer):
try:
..................
..................
..................
..................
return Response(status=status.HTTP_200_OK, data={
"message":'link sent successfully'})
except Exception as e:
print('except block of the decorated function')
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
data={"message" : 'error sending link'})
This is printing the line
except block of the decorated function
and not the line
except block of the decorator
If I remove the Except block from the decorated function then the except block of the decorator is getting executed.
Any help in understanding how this exception trace is handled in the decorators is appreciated.
This is a normal behaviour: you run target_function from the decorator and you catch the exception inside it, so it is not seen by the decorator. I think you have to raise the exception in the target_function, as you done in the decorator. But as you have to return a Response in the except of the decorated function, the problem seems hard to solve...