Skip to content

Instantly share code, notes, and snippets.

@ekreutz
Last active October 18, 2023 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekreutz/db9bdc51456a2b98982345855e5d531b to your computer and use it in GitHub Desktop.
Save ekreutz/db9bdc51456a2b98982345855e5d531b to your computer and use it in GitHub Desktop.
Asyncio error antipattern

An antipattern in python asyncio error handling

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!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment