Question

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

I thought I can use response.getResponseCode() to check the response code, but I'm not able to, for e.g when there is 404 error, the script not continue and just stop at UrlFetchApp.fetch

Was it helpful?

Solution

Edit: This parameter is now documented here.

You can use the undocumented advanced option "muteHttpExceptions" to disable exceptions when a non-200 status code is returned, and then inspect the status code of the response. More information and an example is available on this issue.

OTHER TIPS

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.

why don't you use try catch and handle the error in catch block

try{
    //Your original code, UrlFetch etc
  }
  catch(e){
    // Logger.log(e);
    //Handle error e here 
    // Parse e to get the response code
  }

You can manually parse the caught error, but it's not recommended. When catching the exception (that is being thrown in case muteHttpExceptions is turned off), the error object would be in the following format:

{
   "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___"
}

If you for some reason prefer not using muteHttpExceptions, you could catch the exception e, look at e.message, substring the text between "Truncated server response: " and " (use muteHttpExceptions option to examine full response)", JSON.parse() it, and the returned object would be the error returned from the api call.

I wouldn't suggest it over muteHttpExceptions, just wanted to show the best way to get the error object this way.

Anyways, try-catch your UrlFetchApp.fetch() call to make sure you catch the unhandled exceptions, like 404.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top