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

Javascript如何捕获控制台报错Failed to load resource: net::ERR_TIMED_OUT

net::ERR_TIMED_OUT 错误的正确捕获方案

现有方案失效原因

  • try/catch仅能捕获同步执行上下文内的运行时错误,网络请求属于异步IO操作,错误抛出时已经脱离了try/catch的执行上下文,因此无法捕获。
  • 单纯绑定xhr.onerror未捕获到超时错误,是因为ERR_TIMED_OUT会优先触发xhr.ontimeout事件,而非onerror,两者需要同时配置才能覆盖所有网络错误场景。

各场景下的正确捕获方法

1. 原生XHR请求场景

同时绑定ontimeout、onerror事件,并明确配置timeout超时阈值即可捕获该错误,示例代码:

const xhr = new XMLHttpRequest();
xhr.open('GET', '/请求地址', true);
// 自定义超时时间,单位为毫秒
xhr.timeout = 10000;
// 专门捕获超时类错误
xhr.ontimeout = () => {
  console.error('已捕获net::ERR_TIMED_OUT错误');
  // 自定义错误处理逻辑
};
// 捕获其他网络错误(DNS解析失败、无网络、跨域拦截等)
xhr.onerror = (e) => {
  console.error('捕获到其他网络错误:', e);
};
xhr.onload = () => {
  // 正常请求响应处理逻辑
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log('请求成功', xhr.responseText);
  }
};
xhr.send();

2. Fetch API请求场景

Fetch没有内置超时事件,需要结合AbortController实现超时控制和错误捕获,示例代码:

const controller = new AbortController();
// 配置10秒超时
const timer = setTimeout(() => controller.abort(), 10000);

fetch('/请求地址', {
  signal: controller.signal
}).then(res => {
  clearTimeout(timer);
  if (!res.ok) throw new Error(`响应错误: ${res.status}`);
  return res.json();
}).then(data => {
  console.log('请求成功', data);
}).catch(err => {
  // 匹配超时触发的中止错误
  if (err.name === 'AbortError') {
    console.error('已捕获net::ERR_TIMED_OUT错误');
  } else {
    console.error('其他请求错误:', err);
  }
});

3. 全局捕获所有网络资源错误

如果需要全局捕获页面内所有接口、静态资源(图片、脚本、样式表)的加载错误,可以监听window的error事件,需要开启捕获阶段监听才能拿到网络类错误:

window.addEventListener('error', (e) => {
  // 过滤出资源/请求类错误
  if ([XMLHttpRequest, HTMLScriptElement, HTMLLinkElement, HTMLImageElement].some(cls => e.target instanceof cls)) {
    console.error('全局捕获到资源加载错误:', e);
  }
}, true);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:45:02