hhsb
hhsb

Reputation: 582

HTTP failure callback for UrlFetchApp.fetch() in gmail addon

I would like to write a callback when a HTTP requests fails. How do I chain it to UrlFetchApp.fetch()? Please refer to the HTTP request below.

// Make a GET request. UrlFetchApp.fetch('http://www.google.com/');

Upvotes: 3

Views: 996

Answers (1)

King Holly
King Holly

Reputation: 996

Please note that the fetch function is synchronous. It does not provide a callback parameter and does not return a promise.

An approach to catching exceptions is possible through the UrlFetchApp.fetch(url, params) function. You can pass the muteHttpExceptions parameter into the params location of the function call. That way you can inspect the response code yourself and respond appropriately. Documentation: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchurl-params

UrlFetchApp.fetch('http://www.google.com/', {muteHttpExceptions: true});

muteHttpExceptions (Boolean) if this is set to true, the fetch will not throw an exception if the response code indicates failure, and will instead return the HTTPResponse (default: false)

An alternative would be a simple try/catch statement. I imagine you could log the error or respond appropriately.

try {
   UrlFetchApp.fetch('http://www.google.com/');
}
catch(e) {
   // e contains error response
}

Upvotes: 3

Related Questions