繁体   English   中英

在 function 末尾检查执行错误的代码?

[英]Code to check for execution error at end of function?

我创建了一个在谷歌表格文件上运行的谷歌应用脚本。 每天上午 9 点左右,我的函数都会触发一个触发器。

每隔几天(我不知道为什么),但我得到一个

Execution Error: Service invoked too many times for one day: urlfetch

我已经放弃尝试解决这个问题,但是如果在我的 function 结束时我可以包含一些代码来检查是否存在执行错误,如果是这样运行另一个 function,例如

myfunction_9am() {
    <try run some code>
    if (execution Status = "Failed") {      <<this is the bit I don't know how to code
        myfunction_error();
    }
}

Apps 脚本中的错误处理可以通过 JavaScript 和 Apps 脚本故障排除工具进行处理。

function myFunction() {
try{
  //Some code 
}catch(e) {
  //Code to run only if there is an error
  console.error("Error: " + e + "Stack: " + e.stack);//Send to StackDriver
  myErrorHandlingFunction(e);
} 
}

错误处理 function:

function myErrorHandlingFunction(e) {
  var body,errMsg, recipient,stack;

  if (!e) {
    return;
  }

  errMsg = e.message;
  stack = e.stack;

  recipient = Session.getEffectiveUser().getEmail();
  subject = "Error in Code";

  body = 'The error is: ' + errMsg + "\n\nStack:" + stack;
  GmailApp.sendEmail(recipient, subject, body);
}

括号中的字母e是一个“异常对象”,其中包含 JavaScript 错误消息和“堆栈”。 如果 catch 块运行代码,则执行失败。 您无需测试它是否失败。 要获取错误消息,请使用e.message并获取堆栈使用e.stack

您可能希望将错误信息发送到 Apps Script StackDriver 服务和/或通过您自己的代码处理错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM