You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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状态。

问题根源

  1. 语法错误:缺少try关键字,except块无法和async with代码块关联,导致异常未被捕获直接抛出。
  2. 异常捕获不精准:捕获的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 00:26:04