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

Python requests报WinError 10060超时异常无法捕获如何解决

问题背景
  • 现有脚本用于遍历电商平台商品、校验分销商库存,代码位于for循环结构内,except块末尾添加了continue关键字以实现报错后跳过当前轮次继续循环。脚本运行时间歇性抛出如下系统层错误:
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
  • 原有逻辑默认except requests.exceptions.RequestException as _error:可以捕获所有requests库抛出的请求相关错误,但实际运行中上述超时异常未被捕获,直接中断了循环执行。涉及的原有代码如下:
try:
    print("Line 85")
    Check_BC_API_CALLS()
    print("Line 87")
    r2 = requests.get('https://api.bigcommerce.com/stores/' + _BcStoreHash + '/v3/catalog/products?page=' + str(_CurrentPage) + '&limit=1', headers=_BcHeaders)
    print("Line 90")
except requests.exceptions.RequestException as _error:
    print("BigCommerce request failed: " + _error)
    Check_BC_API_CALLS()
    continue
故障原因
  1. 抛出的WinError 10060是Windows系统层面触发的TCP连接超时错误,属于Python内置OSError的子类。当连接在requests库完成异常封装前就被系统网络层中断时,该错误不会被自动包装为requests.exceptions.RequestException的子类,因此原有捕获逻辑无法命中。
  2. 原有except块存在语法隐患:异常对象_error不能直接与字符串拼接,触发该分支时会额外抛出TypeError: can only concatenate str (not "Exception") to str错误。
  3. 原有requests请求未显式设置timeout参数,极端情况下会出现请求无限挂起的问题。
修复方案
  • 扩展异常捕获范围,同时覆盖requests库的请求异常、系统层面的超时/网络IO错误
  • 修复异常打印的类型错误,将异常对象转为字符串后输出
  • 为requests请求显式设置连接、读取超时阈值,避免请求无期限挂起

修复后的代码参考:

try:
    print("Line 85")
    Check_BC_API_CALLS()
    print("Line 87")
    # 元组第一个值为连接超时时间,第二个为读取超时时间,单位为秒,可根据实际业务调整
    r2 = requests.get(
        f'https://api.bigcommerce.com/stores/{_BcStoreHash}/v3/catalog/products?page={_CurrentPage}&limit=1',
        headers=_BcHeaders,
        timeout=(10, 30)
    )
    print("Line 90")
# 同时捕获requests请求异常、系统层网络超时/IO错误
except (requests.exceptions.RequestException, TimeoutError, OSError) as _error:
    print(f"BigCommerce request failed: {str(_error)}")
    Check_BC_API_CALLS()
    continue

若需要做差异化错误处理,可以拆分多个except块分别捕获不同类型异常,对应执行重试、日志记录、告警等逻辑。如果该类超时错误出现频率较高,建议同步检查本地网络防火墙规则、目标接口是否存在IP限流、网络链路是否存在丢包,从根源降低超时概率。

内容的提问来源于stack exchange,提问作者TxTechnician

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:31:16