有什么方法可以从UrlFetchApp.fetch
中捕获异常?如何捕获UrlFetchApp.fetch异常
我想我可以用response.getResponseCode()
检查响应代码,但我不能,对于例如,当出现404错误,脚本不能继续,只是停留在UrlFetchApp.fetch
有什么方法可以从UrlFetchApp.fetch
中捕获异常?如何捕获UrlFetchApp.fetch异常
我想我可以用response.getResponseCode()
检查响应代码,但我不能,对于例如,当出现404错误,脚本不能继续,只是停留在UrlFetchApp.fetch
编辑:此参数是现在documented here。
您可以使用未记录的高级选项“muteHttpExceptions”在返回非200状态代码时禁用异常,然后检查响应的状态代码。更多信息和示例请参阅this issue。
你为什么不使用尝试捕捉和catch块处理错误
try{
//Your original code, UrlFetch etc
}
catch(e){
// Logger.log(e);
//Handle error e here
// Parse e to get the response code
}
感谢您的快速响应。 当有异常时,是否可以找出响应代码? – louis 2012-07-30 09:43:21
您将在e中得到一个错误字符串,您可以解析该错误字符串以获取错误代码。 – 2012-07-30 09:48:08
诀窍是通过muteHttpExceptions
参数UrlFetchApp.fetch()
。
下面一个例子(未经测试):
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
块。
谢谢,这是我想要的,谷歌应该有这个文件。 – louis 2012-08-06 09:16:15
谢谢,我总是忘记这个功能。 – oshliaer 2014-06-25 08:07:58