如何使用 Google Apps 脚本避免循环中的空对象错误?

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

我正在调用 API 并通过其分页获取数据。但是,当我到达最后一页时,给我最后一页的对象是空的,并且抛出以下错误:TypeError: Cannot convert undefined or null to object此外,我没有最后一页的任何数据。

这是我得到的分页信息:

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

这是我用来获取数据的代码:

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);
}

您可以使用 if 语句和 continue。 IE。替换

const lastPgVal = Object.values(lastPageObj);

来自

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

另一种选择是使用 try...catch

资源