The socket connection was closed unexpectedly. For more information, pass verbos...
错误信息
API Error: The socket connection was closed unexpectedly. For more information, pass verbose: true in the second argument to fetch()
AI 解决方案
🔍 错误分析
1. 🌐 错误翻译
原文:The socket connection was closed unexpectedly. For more information, pass verbose: true in the second argument to fetch()
译文:套接字连接被意外关闭。如需获取更多信息,请在 fetch() 的第二个参数中传递 verbose: true
2. 🎯 原因分析
此错误表明通过
fetch() 发起的网络请求在建立套接字连接后,连接被非正常中断。常见原因包括:3. 💡 解决方案
通过启用详细日志定位具体原因,并在代码中增加重试机制和超时处理。
async function fetchWithRetry(url, options = {}) {
const maxRetries = 3;
const baseDelay = 1000; // 初始延迟 1 秒
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, {
...options,
// 添加超时控制(需配合 AbortController)
signal: AbortSignal.timeout(10000), // 10秒超时
// 启用详细日志
verbose: true,
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
return response;
} catch (error) {
if (attempt === maxRetries - 1) throw error;
// 仅对连接错误重试
if (error.name === 'AbortError' || error.message.includes('socket')) {
const delay = baseDelay * Math.pow(2, attempt); // 指数退避
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
}
// 使用示例
fetchWithRetry('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('最终请求失败:', error));
4. 🛡️ 预防措施
AbortController 设置明确超时,避免连接长时间挂起;控制并发请求量,防止服务器过载拒绝连接