Python异步请求中无法优雅捕获Timeout Exception问题求助
处理aiohttp请求异常:避免程序退出并返回unhealthy状态
问题场景
编写的aiohttp请求代码如下:
async with session.get(endpoint, timeout=10) as response: if response.status != 200: return self.result(endpoint, response.status) except aiohttp.ServerTimeoutError: settings.log.info(f"Host {endpoint} is unreachable") return self.result(endpoint, -1) except TimeoutError: json = {"status": "unhealthy"} settings.log.info(f"Host {endpoint} has timed out") return self.result(endpoint, -1) except aiohttp.client_exceptions.ClientConnectorError: json = { "status": "unhealthy"} settings.log.info(f"Host {endpoint} has timed out") return self.result(endpoint, -1)
请求不可达的endpoint时,抛出asyncio.exceptions.TimeoutError异常,程序意外退出,无法返回预期的unhealthy状态。
问题根源
- 语法错误:缺少
try关键字,except块无法和async with代码块关联,导致异常未被捕获直接抛出。 - 异常捕获不精准:捕获的
TimeoutError不是asyncio模块抛出的对应异常,导致超时异常漏捕。
修复后的代码
import asyncio import aiohttp async def check_health(session, endpoint): try: async with session.get(endpoint, timeout=10) as response: if response.status != 200: return self.result(endpoint, response.status) except aiohttp.ServerTimeoutError: settings.log.info(f"Host {endpoint} is unreachable") return self.result(endpoint, -1) except asyncio.exceptions.TimeoutError: settings.log.info(f"Host {endpoint} has timed out") return self.result(endpoint, -1) except aiohttp.client_exceptions.ClientConnectorError: settings.log.info(f"Host {endpoint} connection failed") return self.result(endpoint, -1)
关键修复点
- 用
try块包裹async with请求代码,确保except能捕获到代码块内抛出的所有异常。 - 明确捕获
asyncio.exceptions.TimeoutError,精准匹配aiohttp请求超时抛出的异常类型。 - 调整日志信息,让不同异常的描述更准确(比如
ClientConnectorError对应连接失败而非超时)。
内容的提问来源于stack exchange,提问作者witty_minds
相关产品推荐
相关产品推荐

