Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda