Skip to content
Advertisement

How to avoid empty object error in a loop using Google Apps Script?

I’m calling an API and getting data going through its pagination. When I get to the last page, though, the obejct giving me the last page is empty and it’s throwing the following error: TypeError: Cannot convert undefined or null to object Besides, I don’t any data from that last page.

Here’s the pagination information I get:

{"count":100,"total":545,"_links":
{
 "self":{
         "href":"/candidates?page=0&per_page=100"
        },
"next":{
        "href":"/candidates?per_page=100"
        },
"last":{
        "href":"/candidates?page=6&per_page=100"
        }
},

Here’s the code I’m using to get the data:

function allcandidates() {
  const url = "https://api.catsone.com/v3/candidates";
  const params = {
    'muteHttpExceptions': true,
    'method': 'GET',
    'redirect': 'follow',
    'headers': {
      'Content-Type': 'application/json',
      'Authorization': 'Token ' + API_KEY
    }
  };

  let pageNum = 1;
  let lastPgNo;

  let data = {}, output = [];

  do {
    let currentUrl = url + '?' + 'per_page=100' + '&' + 'page=' + pageNum;
    //One of their URL parameter is "per_page", which is 25 result/page and it go up to 100. I'm not sure if the fact that the last page doesn't have all 100 results may result in an error, too.

    const response = UrlFetchApp.fetch(currentUrl, params);
    const respCode = response.getResponseCode();
    if (respCode != 200) {
      Browser.msgBox('The server seems to be temporarily down. Please try again later.');
      return;
    }
    //Gets the last page number
    const getText = response.getContentText();
    const lastPageObj = JSON.parse(getText)['_links']['last'];
    const lastPgVal = Object.values(lastPageObj); //This is where the error occurs
    const lastPgText = lastPgVal.toString();
    lastPgNo = Number(lastPgText.split('?page=').pop().split('&')[0])

    //Gets current page
    const currentPageObj = JSON.parse(getText)['_links']['self'];
    const currentPgVal = Object.values(currentPageObj);
    const nextPgText = currentPgVal.toString();
    var currentPgNo = Number(nextPgText.split('?page=').pop().split('&')[0])

    const dataSet = JSON.parse(getText)['_embedded']['candidates'];
    for (let i = 0; i < dataSet.length; i++) {
      data = dataSet[i];
      output.push([data.id]);
    }
    pageNum = pageNum + 1;
  } while (pageNum <= lastPgNo);
}

Advertisement

Answer

You might use an if statement and continue. I.E. replace

const lastPgVal = Object.values(lastPageObj);

by

if(lastPageObj){
  const lastPgVal = Object.values(lastPageObj);
} else {
  continue;
}

Another option is to use try...catch

Resources

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement