我有一个项目可以读取 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/