Google App脚本:错误处理和停止脚本执行

时间:2020-05-12 09:39:40

标签: google-apps-script google-sheets automation

我正在自动执行由各种数据表组成的Google工作表文档的更新。在此过程中,我正在从“更新”表中读取更新。并根据不同的规则将它们写到其他工作表。下面是我的代码(当前相关的主要功能):

function mainFunction()
{
  //Lock the file while processing is done
  var lock = LockService.getScriptLock();
  lock.tryLock(15000); 
  var updatesSheetName ="Updates";
  var updatesSheet = SpreadsheetApp.getActive().getSheetByName(updatesSheetName); 
  if (updatesSheet==null)
  {
    Logger.log("Retrieve Updates sheet:: Failure");
    //TODO : how to break out of execution and report error
  }
  var updateDataRange = updatesSheet.getDataRange().getValues(); // Read data from 'Updates' row 0 is column names
  if (updateDataRange==null)
  {
    Logger.log("Updates Data retrieve :: Failure");
    //TODO : how to break out of execution and report error
  }  
  Logger.log("Retrieve Updates sheet :: Succesful");        
  Logger.log("Updates Data Matrix retrieve :: Succesful");

  var updatesDataToWrite = processData(updateDataRange); // From ExecutionMethod.gs
  if (updatesDataToWrite!=null)
  {
    Logger.log("Processing updates data :: Succesful");
    updateDataRange=updatesDataToWrite;
    updateDataSheet(updateDataRange,"Updates"); // Write new Updates Matrix to 'Updates' sheet 
    Logger.log("Clean Updates sheet::succesfuly");
    if (updateDataRange.length>1)
    {
      Logger.log("Not All Updates were processed : Please check Errors");
    }
    //updateMainSheet(); need to understand logic    
  }
  else if (updatesDataToWrite==null)
  {
    Logger.log("Processing updates data :: Failure");
  }  
  lock.releaseLock();
}

我要弄清楚的是在数据读取失败的情况下如何恢复/停止执行:

updatesSheet==null

如何完全停止执行?以编程方式? 我找不到任何可以在线或在Google应用程序脚本参考中关联/使用的东西

1 个答案:

答案 0 :(得分:0)

如果要退出该函数,请使用return,即

function someFun () {
    if( someCondition ) {
     // say you want to stop the whole function, then do this
      return
    }
    // The code below here will not run
}