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

Gmail插件中UrlFetchApp.fetch()的HTTP请求失败回调实现方法

如何给UrlFetchApp.fetch()添加链式调用的失败回调

嘿,我来给你捋清楚怎么实现这个需求~ 首先得明确:原生的UrlFetchApp.fetch()是同步阻塞式的方法,它在请求失败时会直接抛出异常,本身并不支持链式调用的语法。要实现带失败回调的链式调用,我们需要把它包装成Promise风格的异步函数,这样就能用.then()处理成功、.catch()处理失败(也就是你的失败回调)了。

下面是具体的实现步骤和示例:

1. 封装Promise风格的fetch函数

先写一个包装函数,把原生的UrlFetchApp.fetch()放进Promise里,成功时resolve响应对象,失败时reject错误信息:

function fetchWithPromise(url, options = {}) {
  return new Promise((resolve, reject) => {
    try {
      // 执行原生的fetch请求
      const response = UrlFetchApp.fetch(url, options);
      // 请求成功,把响应传递给后续的.then()
      resolve(response);
    } catch (error) {
      // 请求失败,把错误传递给后续的.catch()
      reject(error);
    }
  });
}

2. 链式调用并添加失败回调

现在就可以像使用异步API一样链式调用这个封装后的函数,.catch()就是你要的失败回调位置:

// 链式调用示例(模拟你的GET请求)
fetchWithPromise('http://www.google.com/')
  .then(response => {
    // 成功回调:处理请求结果
    console.log('请求成功!响应状态码:', response.getResponseCode());
    console.log('响应内容:', response.getContentText());
  })
  .catch(error => {
    // 失败回调:处理请求错误
    console.error('请求失败了:', error.message);
    // 这里可以添加你的自定义失败逻辑,比如记录日志、触发告警、重试请求等
  });

额外说明

  • 如果你的场景必须用同步代码处理失败,也可以直接用try/catch包裹原生的UrlFetchApp.fetch(),但这种方式没法实现链式调用:
try {
  const response = UrlFetchApp.fetch('http://www.google.com/');
  // 处理成功逻辑
} catch (error) {
  // 处理失败逻辑
  console.error('请求失败:', error.message);
}
  • 封装的fetchWithPromise函数还支持传入options参数(比如请求方法、 headers、请求体等),用法和原生UrlFetchApp.fetch()完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:42:04