Handle 404 errors in UrlFetchApp.fetch ()

I am creating an extension in Google Spreadsheets and I am trying to handle the 404 error that urlFetch () can provide. Now it just shows a popup at the top of the table:

http://i.stack.imgur.com/fvCPC.png

This is the code I have:

function doTestAPICall() {
  var headers = {
    'Authorization': 'Basic ' + Utilities.base64Encode(user + "/token:" + token)
  };
  var url = "https://" + subdomain + ".domain.com/api/v2/users/me.json";
  var options = {
    'contentType': 'application/json',
    'method': 'get',
    'headers': headers
  };
  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() == 200){
    var json = response.getContent();
    var data = JSON.parse(json);
    if(data.user.email != user){
      return false;
    } else {
      //User was correctly authenticated
      return true;
  }else{
    return false;
  }
}

However, the function never receives response.getResponseCode (), since it no longer works in the UrlFetchApp.fetch function. Any ideas / suggestions on how I can handle this?

Thank!

--- EDIT ---

As per Amit's suggestion, adding muteHttpExceptions in the UrlFetchApp parameters solved the problem.

Now the code is as follows:

function doTestAPICall() {
  var headers = {
    'Authorization': 'Basic ' + Utilities.base64Encode(user + "/token:" + token)
  };
  var url = "https://" + subdomain + ".domain.com/api/v2/users/me.json";
  var options = {
    'contentType': 'application/json',
    'method': 'get',
    'headers': headers,
    'muteHttpExceptions': true
  };
  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() == 200){
    var json = response.getContentText();
    var data = JSON.parse(json);
    if(data.user.email != user){
      return false;
    } else {
      //User was correctly authenticated
      return true;
  }else{
    return false;
  }
}
+2
source share
1 answer

muteHttpExceptions true HTTP-, .

function fetchPage() {
  var response = UrlFetchApp.fetch("http://ctrlq.org/404", {muteHttpExceptions: true});
  if (response.getResponseCode() == 404) {
    Logger.log("Web page not found");
  }
}
+4

Source: https://habr.com/ru/post/1656626/


All Articles