如何制作一个装饰器来用try-except语句包装异步函数



假设我有一个异步函数,如下所示:

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

我想制作一个装饰器,并在这个函数上使用它,它将上面的代码包装在一个try-except语句中,如下所示:

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

有办法做到这一点吗?

因为包装器首先被调用,我们还应该将其定义为异步函数: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"))
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)

最新更新