无法从未定义的 Youtube Analytics API 错误中读取 属性 "length"

Cannot read property "length" from undefined, Youtube Analytics API Error

我是 Youtube Analytics Api 的新手,我在 google 中关注 this guide 以将我的分析报告保存在 google sheet 使用 Google Apps Script。每次我 运行 脚本,我都会得到这样的错误,

TypeError: Cannot read property "length" from undefined.

这是代码,

  function spreadsheetAnalytics() {
  // Get the channel ID
  var myChannels = YouTube.Channels.list('id', {mine: true});
  var channel = myChannels.items[0];
  var channelId = channel.id;
  // Set the dates for our report
  var today = new Date();
  var oneMonthAgo = new Date();
  oneMonthAgo.setMonth(today.getMonth() - 1);
  var todayFormatted = Utilities.formatDate(today, 'UTC', 'yyyy-MM-dd')
  var oneMonthAgoFormatted = Utilities.formatDate(oneMonthAgo, 'UTC', 'yyyy-MM-dd');

    var analyticsResponse = YouTubeAnalytics.Reports.query(
        'channel==' + channelId,
        oneMonthAgoFormatted,
        todayFormatted,
        'views,likes,dislikes,shares',
        {
          dimensions: 'day',
          sort: '-day'
        });

  var ssName = 'YouTube channel report ' + oneMonthAgoFormatted + ' - ' + todayFormatted;
  var numRows = analyticsResponse.rows.length;  // ERROR IN THIS LINE
  var numCols = analyticsResponse.columnHeaders.length;

  var ssNew = SpreadsheetApp.create(ssName, numRows + 1, numCols);
  var sheet = ssNew.getSheets()[0];

  // Get the range for the title columns
  // Remember, spreadsheets are 1-indexed, whereas arrays are 0-indexed
  var headersRange = sheet.getRange(1, 1, 1, numCols);
  var headers = [];

  // These column headers will correspond with the metrics requested
  // in the initial call: views, likes, dislikes, shares
  for(var i in analyticsResponse.columnHeaders) {
    var columnHeader = analyticsResponse.columnHeaders[i];
    var columnName = columnHeader.name;
    headers[i] = columnName;
  }

  headersRange.setValues([headers]);

  headersRange.setFontWeight('bold');
  sheet.setFrozenRows(1);

  var dataRange = sheet.getRange(2, 1, numRows, numCols);
  dataRange.setValues(analyticsResponse.rows);

  var dateHeaders = sheet.getRange(1, 1, numRows, 1);
  dateHeaders.setFontWeight('bold');
  sheet.setFrozenColumns(1);

  var range = sheet.getRange(1, 1, numRows, numCols);
  var chart = sheet.newChart()
                   .asColumnChart()
                   .setStacked()
                   .addRange(range)
                   .setPosition(4, 2, 10, 10)
                   .build();
  sheet.insertChart(chart);
}

我没有编辑指南中的任何代码。完全按照给出的内容进行操作。我怎样才能摆脱这个错误?

就像错误说 rows 未定义一样。这是因为该查询没有返回数据。

来自以下位置的文档:https://developers.google.com/youtube/analytics/v1/reference/reports/query#response

If no data is available for the given query, the rows element will be omitted from the response.