stream disconnected before completion: stream closed before response.completed

2026年10月23日 11:27 14.22 秒 success

错误信息

stream disconnected before completion: stream closed before response.completed

AI 解决方案

原文:stream disconnected before completion: stream closed before response.completed
译文:流在完成前已断开:流在响应完成之前被关闭

🎯 原因分析


该错误表示在流式数据传输过程中,连接在服务器未完成响应前就被意外终止,常见于以下场景:
  • 网络波动或中断导致连接断开

  • 服务器端流式响应过程中发生异常或主动关闭连接

  • 客户端提前终止了流的接收(如未正确处理异步流)
  • 💡 解决方案


    检查流式请求和接收逻辑,确保完整处理流的生命周期:

    # 示例:Python中使用流式请求的正确写法
    import httpx
    
    try:
        with httpx.stream(
            "GET",
            "https://api.example.com/stream",
            timeout=httpx.Timeout(30.0)
        ) as response:
            response.raise_for_status()
            for chunk in response.iter_lines():
                if chunk:
                    print(chunk)
    except httpx.StreamError as e:
        print(f"流式请求出错: {e}")
    except Exception as e:
        print(f"其他错误: {e}")
    

    🛡️ 预防措施


  • 合理设置超时:为流式请求配置足够长的超时时间,避免因传输慢导致提前关闭

  • 增强错误处理:对流式连接的中断进行捕获,支持重试机制,确保网络波动时能恢复连接

  • 使用断点续传:对于关键数据流,可记录已接收的偏移量,连接断开后从断点继续接收