Reputation: 2306
I am using asyncio, and I have noticed that exception do not get raised within async functions.
I have created a sample of the problem I am facing, where my async function looks like:
async def async_fun(foo):
try:
get_foo = await some_thing_async(bar)
except Exception as E:
raise E # Does not raise exception :(
Which I gather and run like:
async def main():
await asyncio.gather(async_fun("baz"), return_exceptions=True)
asyncio.run(main())
How can I propagate exceptions from async_fun
? I want to be able to raise exceptions if they occur. Happy to provide further information if needed.
Upvotes: 1
Views: 1480
Reputation: 154856
return_exceptions=True
explicitly tells asyncio.gather()
to return exceptions raised by awaitables, instead of propagating them which is the default behavior. Since you don't examine the return value of asyncio.gather()
, you have no way of noticing the exceptions.
To fix the issue, just remove return_exceptions=True
from the invocation of asyncio.gather
:
async def main():
await asyncio.gather(async_fun("baz"))
Also note that if you only await one function, asyncio.gather
is unnecessary, so the above could have been written more shortly as await async_fun("baz")
.
Upvotes: 1