Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

271
Vistas
Handling exception through a decorator in Django

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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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...

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda