lou*_*uis 16 google-apps-script
有没有办法从中捕获异常UrlFetchApp.fetch?
我以为我可以用它response.getResponseCode()来检查响应代码,但我无法,例如当有404错误时,脚本不会继续并且只是停在UrlFetchApp.fetch
Ald*_*uca 14
诀窍是传递的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))
// ...
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,如果URL不可用(例如,您尝试使用的服务已关闭),它仍然看起来像是抛出错误,因此您可能仍需要使用try/catch块.
| 归档时间: |
|
| 查看次数: |
21832 次 |
| 最近记录: |