Google Apps脚本中未处理的例外情况

ten*_*its 7 javascript exception-handling google-sheets google-apps-script

我创建了一个公共Web应用程序,可以访问我的私人电子表格数据.我可以捕获并记录异常try..catch,但是:

  1. 是否可以捕获所有未处理的异常,如浏览器window.onerror
  2. 我可以在某处查看未处理的异常日志吗?
  3. 通过诸如"服务调用太多次"之类的例外我的应用程序甚至没有运行,所以在这里我绝对不能处理异常.是否有这种例外的日志?

这些都是如此简单的问题,所以我很困惑地问他们,但经过几个小时的研究后我找不到答案.

先感谢您.

Spe*_*ton 7

这些是目前正在解决的问题.现在,在Apps脚本中,早期访问计划是处理这些案例的两个新增功能.第一个是与stackdriver日志记录的本机集成和添加google.script.run.withLogger().

首先,您需要申请EAP:

https://developers.google.com/apps-script/guides/apps-script-eap

堆栈驱动器记录:

要记录到stackdriver,该console对象已添加到服务器端.

code.gs

console.log('This will log to stackdriver')  
Run Code Online (Sandbox Code Playgroud)

查看所有方法的文档console.

https://developers.google.com/apps-script/guides/logging#stackdriver_logging

来自文档的示例:

function measuringExecutionTime() {
  // A simple INFO log message, using sprintf() formatting.
  console.info('Timing the %s function (%d arguments)', 'myFunction', 1);

  // Log a JSON object at a DEBUG level. The log is labeled
  // with the message string in the log viewer, and the JSON content
  // is displayed in the expanded log structure under "structPayload".
  var parameters = {
      isValid: true,
      content: 'some string',
      timestamp: new Date()
  };
  console.log({message: 'Function Input', initialData: parameters});

  var label = 'myFunction() time';  // Labels the timing log entry.
  console.time(label);              // Starts the timer.
  try {
    myFunction(parameters);         // Function to time.
  } catch (e) {
    // Logs an ERROR message.
    console.error('myFunction() yielded an error: ' + e);
  }
  console.timeEnd(label);     
  }
Run Code Online (Sandbox Code Playgroud)

此外,您还可以检查Log Exceptions脚本属性.每次脚本中发生任何错误时,都会生成一个stackdriver条目.

Web应用程序中的错误恢复

要从失败中恢复Web应用程序,您可以访问对象中withFailureHandler()找到的方法google.script.run.有了这个,您可以在脚本遇到异常的情况下注册回调.

完整文档可在以下位置找到:

https://developers.google.com/apps-script/guides/html/reference/run

如果您正在进行服务器端检查,则try...catch可能会收到异常但正常处理它.在这种情况下,withFailureHandler()将不会执行,onSuccessHandler()可能不是处理错误的最佳位置.在EAP中,现在有一种withLogger方法可以实现google.script.run.目前还没有文档google.script.run.withLogger().我通过挖掘devtools找到了它.withLogger()允许您在创建堆栈驱动程序条目时将函数注册为回调.在log exceptions签入脚本属性后,这尤其有用.在这个意义上它有点像withFailureHandler()但它可以通过服务器端console对象添加的任何堆栈驱动程序条目触发.

的index.html

<script>
  google.script.run
        .withSuccessHandler(function(){console.log('OK')})
        .withFailureHandler(function(e){console.error(e)})
        .withLogger(function(e){console.warn("The following log was generated:"+e)})
        .serverFunctionCall();
</script>
Run Code Online (Sandbox Code Playgroud)

code.gs

function serverFunctionCall(){
   console.log("This log will generate a callback");
   return true;

}
Run Code Online (Sandbox Code Playgroud)