调试应用程序脚本

问题描述 投票:0回答:1

我目前正在Apps Scripts中编写相当大量的代码,调试小事情变得很麻烦。

例如,我没有放置“SpreadsheetApp”,而是放置了“SpreadsHeetApp”,尽管 Apps 脚本让我意识到了此错误,但它并没有告诉我这是在哪一行代码!

如果您运行单个函数,Apps Scripts 会提供执行日志,但当您从工作表运行它时,这似乎不可用。

我错过了什么吗?有没有更好的方法来记录和读取 Apps 脚本中的错误?

javascript google-apps-script
1个回答
0
投票

我养成了总是将函数包装在 try catch 块中的习惯。这样我就创建了一个原始的回溯。您甚至可以创建自己的错误消息,如替代

debug2
所示。

代码.gs

function debug() {
  try {
    debug1();
  }
  catch(err) {
    console.log("Error in debug:"+err);
  }
}

function debug1() {
  try {
    debug2();
  }
  catch(err) {
    throw "\nError in debug1: "+err;
  }
}

function debug2() {
  try {
    let a = 1;
    let b = 2;
    let c = 3;
    let x = a/b;
    let y = c/d;
  }
  catch(err) {
    throw "\nError in debug2: "+err;
  }
}

执行日志

7:04:13 AM  Notice  Execution started
7:04:14 AM  Info    Error in debug:
                    Error in debug1: 
                    Error in debug2: ReferenceError: d is not defined
7:04:13 AM  Notice  Execution completed

替代调试2

function debug2() {
  try {
    let a = 1;
    let b = 2;
    let c = 3;
    let d = 0;
    if( d === 0 ) throw "d is zero";
    let x = a/b;
    let y = c/d;
  }
  catch(err) {
    throw "\nError in debug2: "+err;
  }
}

执行日志

7:10:45 AM  Notice  Execution started
7:10:46 AM  Info    Error in debug:
                    Error in debug1: 
                    Error in debug2: d is zero
7:10:46 AM  Notice  Execution completed
© www.soinside.com 2019 - 2024. All rights reserved.