当 JSON 属性 不存在时如何处理 Google 工作表中的#Error?

How to handle #Error in Google Sheets when a JSON property does not exist?

我在 Google 表格中使用以下脚本从 Yahoo!Finance 中检索某些公司(以股票代码表示)属性(在 JSON 中)并将它们显示在 [= 中的相邻单元格中=28=].

我正在检索 3 个属性;将来会扩展此列表。我目前正在尝试实现正确的错误处理。

 function yahooFinance(symbol) {
  const url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' + encodeURI(symbol)
    + '?modules=price,assetProfile,summaryDetail,incomeStatementHistory,'
    + 'balanceSheetHistory,defaultKeyStatistics,financialData,calendarEvents,'
    + 'recommendationTrend,upgradeDowngradeHistory,majorHoldersBreakdown'
    ;
  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
  const responseCode = response.getResponseCode();
  if (responseCode === 200) {
    const quote = JSON.parse(response.getContentText());
    const summaryDetail = quote.quoteSummary.result[0].summaryDetail;

    const divYield = summaryDetail.dividendYield.fmt  || "-";
    const payoutRatio = summaryDetail.payoutRatio.fmt || "-";
    const marketCap = summaryDetail.marketCap.fmt     || "-";

    return [[ divYield , payoutRatio, marketCap ]];
  }
  else {
    return "-";
  }
}

问题是:如果某个属性对于某个符号不存在,Google张return会报错:#Error TypeError: Cannot read property 'marketCap' of undefined (line 43).

我的问题是:在这种情况下,我怎么还能 return 一个 -(连字符)?

考虑为要绑定值的单元格设置一个公式。

改编自此 answer 的示例:

var cell = sheet.getRange("B5");
cell.setFormula("=IFNA(B5,'Invalid value')");

将代码行替换为

const marketCap = summaryDetail.marketCap == null ? '-' : summaryDetail.marketCap.fmt;