Sphere
Log in Join
☆ 3

asyncio.gather silently swallowing exceptions since 3.11

I've got a worker that fires off about twenty coroutines with asyncio.gather(..., return_exceptions=True). Since moving to Python 3.11 I'm getting weird results — one task raises a TimeoutError and instead of seeing it in my logs I just get the exception object mixed into my results list. My try/except around the gather never fires. What's the idiomatic way to log which coroutine failed without losing the successful results? I can't just drop return_exceptions because one bad task kills the whole batch. Slightly losing my mind here.

⚑ Report

4 replies

☆ 0
N nginx ·2026-09-30#1

return_exceptions=True literally means exceptions get returned as values, so your try/except won't ever see them. That's by design, not a 3.11 regression. You need to iterate the results and check isinstance(r, BaseException). Also worth noting a CancelledError is a BaseException now, not an Exception, so it won't be caught by a plain except Exception — that bit me last week in a nearly identical setup.

⚑ Report
☆ 0
D docker ·2026-10-03#2

Ah okay, that explains it. I was on 3.10 before and swear it behaved differently, but maybe I just never hit the failure path. Iterating works, but how do I know which coroutine produced which exception? The results list is in order but my tasks are built dynamically from a dict, so I only have the keys, not a stable index I trust. Is there a cleaner way than zipping?

⚑ Report
☆ 0
D duct ·2026-10-12#3

Zip your original keys with the results. Something like for key, res in zip(keys, results): if isinstance(res, BaseException): log.error('%s failed: %r', key, res). If you need a real traceback, store it when you build the task — exceptions returned by gather don't reliably carry the original traceback after the fact, only the __traceback__ on the object which is usually useless by the time you get around to logging it.

⚑ Report
☆ 0
Y yaml5 ·2026-10-19#4

Small addition: if you do want tracebacks, wrap each coroutine in a helper that catches the error and returns (key, value, traceback.format_exc()). That's what we ended up doing after two incidents where the logs said 'failed' with no context. Also return_exceptions won't save you from a task that gets cancelled externally — those come back as CancelledError objects you probably want to re-raise rather than treat as a normal failure.

⚑ Report
Log in to reply.