Don't do this:
The try catch will catch any instance of SomeError, even if it's not emitted inside my_async_function
.
This happens if my_async_function
runs for long enough so that SomeError
is emitted elsewhere in the
program, while this piece of code is still inside the try-except.
try:
result = await my_async_function()
except SomeError:
print("Error happened!")
Instead always do this: EDIT: this is not valid
await (task := asyncio.create_task(my_async_function()))
if (e := task.exception()) is not None:
print("Error happened!")
else:
result = task.result()
Note that this is still fine:
try:
# Here we're calling a regular synchronous function, so it's fine.
result = my_sync_function()
except SomeError:
print("Error happened!")