NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior0 views

How do you handle errors and timeouts in asynchronous code? Give an example.

Practice

AI answer

I set a timeout, handle expected exceptions at the appropriate level, and don’t suppress task cancellation. I retry requests only for temporary errors and with a limited number of attempts, preferably with a delay and jitter.

import asyncio

async def fetch_data(client, url):
    try:
        async with asyncio.timeout(5):  # Python 3.11+
            return await client.get(url)
    except TimeoutError:
        # Log the context or convert the error to a domain-specific one
        raise RuntimeError(f"Request timed out: {url}")
    except asyncio.CancelledError:
        # Allow the calling code to cancel the task correctly
        raise
    except OSError as exc:
        raise RuntimeError(f"Network error while requesting {url}") from exc

For gather, I determine separately whether it’s acceptable to continue if one task fails; I retain background tasks and make sure to collect their results so exceptions aren’t lost.