如何捕获UrlFetchApp.fetch异常

lou*_*uis 16 google-apps-script

有没有办法从中捕获异常UrlFetchApp.fetch

我以为我可以用它response.getResponseCode()来检查响应代码,但我无法,例如当有404错误时,脚本不会继续并且只是停在UrlFetchApp.fetch

Eri*_*eda 25

编辑:此参数现在记录在此处.

您可以使用未记录的高级选项"muteHttpExceptions"在返回非200状态代码时禁用异常,然后检查响应的状态代码.有关此问题的更多信息和示例.


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块.