有没有办法从UrlFetchApp.fetch
中捕获异常?
我以为我可以使用response.getResponseCode()
来检查回复代码,但我无法做到,例如当出现404错误时,脚本无法继续并且只停留在UrlFetchApp.fetch
答案 0 :(得分:23)
修改:此参数现在为documented here。
您可以使用未记录的高级选项“muteHttpExceptions”在返回非200状态代码时禁用异常,然后检查响应的状态代码。有关this issue的更多信息和示例。
答案 1 :(得分:11)
诀窍是传递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
块。
答案 2 :(得分:4)
为什么不使用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
}
答案 3 :(得分:0)
您可以手动解析捕获的错误,但是不建议这样做。捕获异常(在关闭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
,在“截断的服务器响应:”和“(使用之间“ muttHttpExceptions选项检查完整响应”),JSON.parse()以及返回的对象将是api调用返回的错误。
我不建议在muteHttpExceptions
上使用它,只是想展示以这种方式获取错误对象的最佳方法。
无论如何,请尝试捕获UrlFetchApp.fetch()
调用,以确保捕获未处理的异常,例如404。