如何在Google AppScript中处理外部API返回的404异常?
解决Google AppScript调用API时404异常的处理方案
核心逻辑
Google AppScript的UrlFetchApp.fetch()默认会在API返回4xx/5xx状态码时抛出异常,直接终止脚本。要实现异常捕获并让程序继续,关键是通过muteHttpExceptions: true参数禁用自动抛出异常,手动判断响应状态码后返回对应数据。
实现代码示例
function getAddressData(address) { // 替换为你的实际API地址 const apiUrl = `https://your-api-domain.com/address?query=${encodeURIComponent(address)}`; const requestOptions = { muteHttpExceptions: true, // 核心配置:禁用HTTP状态码自动抛出异常 method: "GET" }; let response; // 捕获网络错误等非HTTP状态码异常 try { response = UrlFetchApp.fetch(apiUrl, requestOptions); } catch (error) { return []; } const statusCode = response.getResponseCode(); // 根据状态码返回对应数据 if (statusCode === 200) { return JSON.parse(response.getContentText()); } else if (statusCode === 404) { return []; } else { // 其他错误状态码可按需处理,这里统一返回空数组 return []; } } // 批量调用测试示例 function batchTest() { const addressList = ["北京市朝阳区", "不存在的测试地址", "上海市黄浦区"]; addressList.forEach(address => { const result = getAddressData(address); console.log(`地址「${address}」返回数据:`, result); }); }
关键细节说明
muteHttpExceptions: true:必须设置该参数,否则API返回404时会直接抛出异常终止脚本。设置后,无论状态码如何,fetch()都会返回完整响应对象,不会中断执行。try-catch块:用于捕获网络连接失败、域名无法解析等非HTTP状态码类的异常,确保这类场景下脚本也能继续运行并返回空数组。- 状态码判断:通过
response.getResponseCode()获取API返回的状态码,精准处理404场景,同时兼容其他错误状态的兜底逻辑。
内容的提问来源于stack exchange,提问作者Joel
相关产品推荐
相关产品推荐

