How do you handle errors and timeouts in asynchronous code? Give an example.
Asked at
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.
Also asked at ГК МЕДСИ
- [name] asked: How does memory management work in Python (garbage collector, reference counting)?
- What is the difference between TaskGroup and the gather function in the asyncio library in Python?
- What solutions did you implement to work around ChatGPT being unavailable from Russian IP addresses?
- How do you scale web application workers (for example, in FastAPI or Django), and which server did you use on your project?
- What blocks the event loop, how do you detect it in production, and what should you do about blocking code?
Similar questions
- How does asynchrony work? When should it be used, and what causes switching between tasks?
- Why use asynchronous programming if the tasks are the same?
- What experience do you have with asynchronous web frameworks, and what kinds of tasks have you used asynchronous programming for?
- How can you make the final line, After, print in this example (how should the error be handled)?
- What is the difference between an asynchronous approach and a multithreaded approach?