javascript - 测试脚本是否正在由交互式调试器运行

标签 javascript google-apps-script

我有一个项目可以读取 Google Sheets 电子表格并在另一个工作表中维护内容摘要。所有钩子(Hook)都已准备就绪,可根据需要(每天、每周等)运行,从上次停止的地方开始,未处理的行将影响摘要。
如果需要清除汇总表并重新处理所有数据,我添加了一个用于重新初始化的菜单选项。在该重新初始化函数中有对话框:

    var ui = SpreadsheetApp.getUi();
    var result = ui.alert(
          "Please confirm"
        , "This will completely wipe out the summary data and start over, and may require many executions in order to catch up.  Are you sure you want to do this?"
        , ui.ButtonSet.YES_NO
          );
    if (result == ui.Button.NO) {
        ui.alert("Good thing I asked!");
        return;
        }

(只有在对摘要进行设计更改时才会发生这种情况。)
如果我在脚本调试器中运行此进程,该进程将终止并显示以下消息:
Exception: Cannot call SpreadsheetApp.getUi() from this context.
所以我想在调试时避免那部分代码。如何确定脚本是否在该模式下运行?

最佳答案

解释:
我想一个简单的解决方案是 try...catch错误。

  • 如果您想检查 具体 错误信息,您可以使用 error属性(property)message它将错误作为字符串返回。
  • 如果错误信息是 预期 错误,即:Cannot call SpreadsheetApp.getUi() from this context然后 继续 与其余的代码。
  • 如果错误是其他错误(在 try 语句中),则 throw那个意外错误和 停止剧本。

  • 解决方法 解决方案 1:
       try {
        var ui = SpreadsheetApp.getUi();
        var result = ui.alert(
              "Please confirm"
            , "This will completely wipe out the summary data and start over, and may require many executions in order to catch up.  Are you sure you want to do this?"
            , ui.ButtonSet.YES_NO
              );
        if (result == ui.Button.NO) {
            ui.alert("Good thing I asked!");
            return;
            }       
       }
       catch(e){
          if(e.message=="Cannot call SpreadsheetApp.getUi() from this context"){
          console.log("the expected error occured, everything is fine"); // the expected error occured, continue
          }
          else{throw e}; // throw the unexpected error and stop the script
       }
       
       // continue with the rest of the code with no issues
    
    解决方法 解决方案 2:
    我只是偶然发现 this answer这可能对你有用。基本上你可以介绍一个"debug"包含“有问题”代码并根据 "debug" 执行此代码的函数中的参数范围。这仍然是需要一些手动干预的变通解决方案,因此我会推荐这个答案的第一个解决方案,它允许您完全控制错误消息。

    关于javascript - 测试脚本是否正在由交互式调试器运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65694780/

    相关文章:

    javascript - PrefixFree.js 正在我的页面上加载额外的 "phantom"样式

    javascript - Node 的 REPL 无法识别 block 代码

    css - 使用转换 :rotate does not pass caja? 的 Htmlservice

    javascript - 来自字符串的链式方法

    javascript - 如何将闭包与函数指针一起使用?

    javascript - 如何为正在查看的网站动态更改 css 样式表?

    javascript - 正则表达式 - 严格验证电子邮件地址本地部分中的名称

    javascript - 数组不能在数据表中使用

    database - 是否可以使用 Google 脚本创建公共(public)数据库(电子表格)搜索?

    google-apps-script - 我如何获得法语区域的日期