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

如何通过用户脚本捕获并处理页面HTTP请求错误?

处理页面HTTP请求错误的用户脚本方案

直接读取控制台输出不是可靠的方案——控制台的输出格式可能随浏览器更新变化,页面脚本也可能覆盖console.error之类的方法干扰捕获,而且无法精准关联到具体的请求信息。更稳妥的方式是直接拦截页面的请求发送接口,在请求失败时触发自定义逻辑。

以下是针对XMLHttpRequest和fetch两种主流请求方式的实现:

1. 拦截XMLHttpRequest

通过重写XMLHttpRequest.prototype.send方法,监听请求的错误、中断事件,同时检查状态码判断请求失败:

// 保存原始send方法
const originalXhrSend = XMLHttpRequest.prototype.send;

XMLHttpRequest.prototype.send = function() {
  // 监听请求错误
  this.addEventListener('error', () => {
    handleRequestFailure('XHR Error', this);
  });
  // 监听请求中断
  this.addEventListener('abort', () => {
    handleRequestFailure('XHR Aborted', this);
  });
  // 监听请求完成,判断状态码
  this.addEventListener('load', () => {
    if (this.status >= 400) {
      handleRequestFailure(`XHR Status Error: ${this.status}`, this);
    }
  });
  // 调用原始方法
  originalXhrSend.apply(this, arguments);
};

function handleRequestFailure(errorType, xhr) {
  // 这里执行你的自定义操作,比如打印信息、弹窗等
  console.log(`捕获到请求失败: ${errorType}`, {
    url: xhr.responseURL,
    method: xhr.method,
    status: xhr.status
  });
  // 示例:弹出提示
  // alert(`请求 ${xhr.responseURL} 失败,请检查网络`);
}

2. 拦截fetch API

重写全局fetch方法,在返回的Promise被reject时,或者响应状态码异常时处理:

// 保存原始fetch方法
const originalFetch = window.fetch;

window.fetch = function(input, init) {
  // 调用原始fetch并处理结果
  return originalFetch(input, init)
    .then(response => {
      // 检查状态码,非2xx视为失败
      if (!response.ok) {
        handleFetchFailure(`Fetch Status Error: ${response.status}`, input, init);
      }
      return response;
    })
    .catch(error => {
      // 捕获网络错误、请求中断等情况
      handleFetchFailure(`Fetch Error: ${error.message}`, input, init);
      // 如需让页面继续处理错误,记得reject
      return Promise.reject(error);
    });
};

function handleFetchFailure(errorType, input, init) {
  // 解析请求URL和方法
  const url = typeof input === 'string' ? input : input.url;
  const method = (init?.method || 'GET').toUpperCase();
  
  // 执行自定义操作
  console.log(`捕获到请求失败: ${errorType}`, { url, method });
  // 示例:记录错误到本地存储
  // localStorage.setItem('lastRequestError', JSON.stringify({ url, method, errorType }));
}

3. 注意事项

  • 确保用户脚本在页面脚本加载前执行(Tampermonkey等工具中设置@run-at document-start),避免遗漏页面早期发送的请求。
  • 多数封装后的请求库(如Axios)底层仍基于XHR或fetch,上述拦截方法依然有效。
  • 不要过度修改原始方法行为,处理完错误后尽量保留页面原有逻辑流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:45:26