How to catch UrlFetchApp.fetch exception

前端 未结 4 716
孤街浪徒
孤街浪徒 2020-12-18 19:26

Is there any way to catch the exception from UrlFetchApp.fetch?

I thought I can use response.getResponseCode() to check the response code,

4条回答
  •  醉酒成梦
    2020-12-18 19:41

    The trick is passing the muteHttpExceptions param of UrlFetchApp.fetch().

    Here an example (untested):

    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))
      // ...
    }
    

    For some reason if the URL is not available (e.g. the service you're trying to use is down) it still looks like is throwing an error so you may still need to use a try/catch block.

提交回复
热议问题