如何在UrlFetchApp.fetch()抛出错误时获取HTTP状态码?
解决Google Apps Script中UrlFetchApp抛出错误后获取HTTP状态码的问题
当UrlFetchApp.fetch()因HTTP错误(如404、429)抛出异常时,你可以通过两种方式获取状态码:
方法1:从捕获的错误对象中获取响应
抛出的Error对象包含response属性,这是完整的HTTPResponse实例,直接调用它的getResponseCode()方法就能拿到状态码。
修改你的GetHttpResponseCode函数:
function GetHttpResponseCode(url) { try { const response = UrlFetchApp.fetch(url); return response.getResponseCode(); } catch (error) { // 错误对象的response属性就是请求响应 if (error.response) { return error.response.getResponseCode(); } // 处理非HTTP错误(比如网络连接失败) throw new Error(`请求失败:${error.message}`); } } GetHttpResponseCode("https://www.google.com/invalidurl") // 返回404
对应重试逻辑的修改:
function FetchURLContents(url) { const maxRetries = 3; for (let attempt = 0; attempt < maxRetries; attempt++) { try { const response = UrlFetchApp.fetch(url); return response.getContentText(); } catch (error) { // 检查是否有HTTP响应 if (!error.response) throw new Error(`请求失败:${error.message}`); const statusCode = error.response.getResponseCode(); if (statusCode === 429) { // 429错误,延迟后重试(这里用指数退避优化等待时间) Utilities.sleep(2000 * (attempt + 1)); } else { // 其他HTTP错误直接抛出 throw new Error(`HTTP错误 ${statusCode}:${error.message}`); } } } throw new Error('多次尝试后仍无法获取URL内容'); }
方法2:使用muteHttpExceptions参数避免抛出异常
调用UrlFetchApp.fetch()时传入{ muteHttpExceptions: true }选项,这样无论HTTP状态码是多少,函数都不会抛出异常,直接返回响应对象,你可以自行判断状态码并处理。
示例实现:
function FetchURLContents(url) { const maxRetries = 3; const fetchOptions = { muteHttpExceptions: true }; for (let attempt = 0; attempt < maxRetries; attempt++) { const response = UrlFetchApp.fetch(url, fetchOptions); const statusCode = response.getResponseCode(); if (statusCode === 200) { return response.getContentText(); } else if (statusCode === 429) { Utilities.sleep(2000 * (attempt + 1)); } else { throw new Error(`HTTP错误 ${statusCode}:无法获取内容`); } } throw new Error('多次尝试后仍无法获取URL内容'); }
这种方式代码更简洁,不需要处理try/catch的异常逻辑,适合需要统一处理所有状态码的场景。
内容的提问来源于stack exchange,提问作者Stevoisiak
相关产品推荐
相关产品推荐

