如何从 asyncio 函数传播异常?

How can I propagate exceptions from asyncio functions?

我正在使用 asyncio,我注意到在异步函数中不会引发异常。

我已经创建了一个我面临的问题的示例,其中我的异步函数如下所示:

async def async_fun(foo):
    try:
        get_foo = await some_thing_async(bar)
    except Exception as E:
        raise E  # Does not raise exception :( 

我收集并运行喜欢的:

async def main():
    await asyncio.gather(async_fun("baz"), return_exceptions=True)


asyncio.run(main())

如何传播来自 async_fun 的异常?如果发生异常,我希望能够提出异常。如果需要,很乐意提供更多信息。

return_exceptions=True 明确告诉 asyncio.gather()return 可等待对象引发的异常,而不是传播它们,这是默认行为。由于您不检查 asyncio.gather() 的 return 值,因此您无法注意到异常。

要解决此问题,只需从 asyncio.gather:

的调用中删除 return_exceptions=True
async def main():
    await asyncio.gather(async_fun("baz"))

另请注意,如果您只等待一个函数,则 asyncio.gather 是不必要的,因此上面的内容可以更简短地写为 await async_fun("baz")