原生JavaScript中Fetch API报“Failed to fetch”偶发错误求助
问题
我们正将网站从jQuery Ajax迁移至原生JavaScript的Fetch API,近期偶发“Failed to fetch”错误。该请求每日触发数百甚至数千次,但仅出现1-2次报错。已配置错误邮件告警,相关代码及错误报告如下:
相关JavaScript代码
async function fetchSimple(url, data = null, attempts = 0) { try { var response = await fetch(url, { method: "POST", body: data, headers: { 'Content-type': 'application/json; charset=UTF-8' } }); if (response.ok) { var responseJSON = await response.json(); return responseJSON.d; } else { throw new Error(`Status: ${response.status}, StatusText ${response.statusText}`); } } catch (error) { attempts++; if (attempts == 1) fetchSimple(url, data, attempts); else { alert(`Failed to ${url}\n\nError Message: ${error.message}\n\nAn email logging the error details has been sent to the development team`); sendErrorLogEmail2(url, error.message, data); } } }
错误报告详情
- 邮件主题:Failed to /Yazzoo/Product.aspx/BuildProductDesignPositionsSectionUI
- 错误信息:Failed to fetch
- 请求数据:
{ "productId":24999 } - 浏览器信息:
{"name":"Chrome","version":"118","screenType":"mobile"}
错误解析与原因分析
错误含义
“Failed to fetch”是Fetch API抛出的网络层通用错误,说明请求并未成功完成:要么请求根本没发送到服务器,要么在接收服务器响应前就因某种原因中断。这类错误和HTTP状态码错误(如404、500)不同,后者会进入response.ok的判断分支,不会触发这个通用错误。
偶发错误的可能原因
结合每日触发数千次仅报错1-2次的场景,大概率是以下低概率环境因素导致:
- 移动端网络波动:用户使用移动设备时,可能遇到临时信号弱、网络切换(WiFi/蜂窝网络切换)、基站信号中断等情况,导致请求中途失败。
- 服务器端临时异常:服务器短时间过载、负载均衡节点切换、服务临时重启等,刚好该请求被波及,这种场景下错误率极低。
- 浏览器层面的限制:Chrome在后台标签页会限制网络资源,或某些网络节流机制触发,导致请求被浏览器终止,这类情况在移动设备上偶发。
代码中的潜在问题
当前重试逻辑存在缺陷:当第一次失败触发重试时,没有返回递归调用的fetchSimple结果,会导致调用者无法获取重试成功后的响应数据。应修改为:
if (attempts == 1) return fetchSimple(url, data, attempts);
内容的提问来源于stack exchange,提问作者Rob_Da_Joyce
相关产品推荐
相关产品推荐

