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

561
Visualizações
How do I make a decorator to wrap an async function with a try except statement?

Let's say I have an async function like this:

async def foobar(argOne, argTwo, argThree):
   print(argOne, argTwo, argThree)

I want to make a decorator and use it on this function in a way that it wraps the above code in a try except statement like this:

try:
   print(argOne, argTwo, argThree)
except:
   print('Something went wrong.)

Is there any way to do this?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

because wrapper called first, we should also define it as a async function: async def wrap(*arg, **kwargs):

import asyncio

def decorator(f):
    async def wrapper(*arg, **kwargs):
        try:
            await f(*arg, **kwargs)
        except Exception as e:
            print('Something went wrong.', e)
    return wrapper


@decorator
async def foobar(argOne, argTwo, argThree):
    print(argOne, argTwo, argThree)
    await asyncio.sleep(1)

asyncio.run(foobar("a", "b", "c"))
over 4 years ago · Santiago Trujillo Relatório

0

def deco(coro1):
    async def coro2(argOne, argTwo, argThree):
        try:
            await coro1(argOne, argTwo, argThree)
        except:
            print('Something went wrong.')
    return coro2

@deco
async def foobar(argOne, argTwo, argThree):
    print(argOne, argTwo, argThree)
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