Python

asyncio.gather with Errors Tolerated

admin by @admin ADMIN
2d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`gather(*tasks)` cancels everything on the first failure — usually NOT what you want. `return_exceptions=True` lets every task finish, returning the exception in place of a result. Perfect for fan-out HTTP fetches.
Python
Raw
import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as r:
        r.raise_for_status()
        return await r.json()

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(
            *(fetch(session, u) for u in urls),
            return_exceptions=True,
        )
    for url, result in zip(urls, results):
        if isinstance(result, BaseException):
            print(f"FAIL {url}: {result}")
        else:
            print(f"OK   {url}: {result}")
    return results

asyncio.run(fetch_all(["https://a.json", "https://b.json", "https://c.json"]))
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.