【发布时间】:2012-07-30 09:28:16
【问题描述】:
有什么方法可以捕获来自UrlFetchApp.fetch 的异常吗?
我以为我可以使用response.getResponseCode() 来检查响应代码,但我不能,例如,当出现 404 错误时,脚本不会继续,只是停在UrlFetchApp.fetch
【问题讨论】:
标签: google-apps-script urlfetch
有什么方法可以捕获来自UrlFetchApp.fetch 的异常吗?
我以为我可以使用response.getResponseCode() 来检查响应代码,但我不能,例如,当出现 404 错误时,脚本不会继续,只是停在UrlFetchApp.fetch
【问题讨论】:
标签: google-apps-script urlfetch
编辑:这个参数现在是documented here。
您可以使用未记录的高级选项“muteHttpExceptions”在返回非 200 状态代码时禁用异常,然后检查响应的状态代码。 this issue 提供更多信息和示例。
【讨论】:
诀窍是传递UrlFetchApp.fetch() 的muteHttpExceptions 参数。
这里是一个例子(未经测试):
var payload = {"value": "key"}
var response = UrlFetchApp.fetch(
url,
{
method: "PUT",
contentType: "application/json",
payload: JSON.stringify(payload),
muteHttpExceptions: true,
}
);
var responseCode = response.getResponseCode()
var responseBody = response.getContentText()
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody)
// ...
} else {
Logger.log(Utilities.formatString("Request failed. Expected 200, got %d: %s", responseCode, responseBody))
// ...
}
由于某种原因,如果 URL 不可用(例如,您尝试使用的服务已关闭),它看起来仍然会引发错误,因此您可能仍需要使用 try/catch 块。
【讨论】:
为什么不使用 try catch 并处理 catch 块中的错误
try{
//Your original code, UrlFetch etc
}
catch(e){
// Logger.log(e);
//Handle error e here
// Parse e to get the response code
}
【讨论】:
e 并不是那么简单,因为 UrlFetchApp 将响应包装在一条短信中。我不会建议这种方法。
您可以手动解析捕获的错误,但不建议这样做。捕获异常时(如果 muteHttpExceptions 关闭则抛出异常),错误对象将采用以下格式:
{
"message": "Request failed for ___ returned code___. Truncated server response: {___SERVER_RESPONSE_OBJECT___} (use muteHttpExceptions option to examine full response)",
"name": "Exception",
"fileName": "___FILE_NAME___",
"lineNumber": ___LINE_NUMBER___,
"stack": "___STACK_DETAILS___"
}
如果您出于某种原因不想使用muteHttpExceptions,您可以捕获异常e,查看e.message,将“截断的服务器响应:”和“之间的文本子串起来(使用 muteHttpExceptions 选项检查完整响应)", JSON.parse() 它,返回的对象就是api调用返回的错误。
我不会在muteHttpExceptions 上推荐它,只是想展示以这种方式获取错误对象的最佳方法。
无论如何,请尝试捕获您的 UrlFetchApp.fetch() 调用,以确保捕获未处理的异常,例如 404。
【讨论】: