简体   繁体   English

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

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

I've created a google app script that runs on a Google Sheets file.我创建了一个在谷歌表格文件上运行的谷歌应用脚本。 Every day at ~9am a trigger runs on of my functions.每天上午 9 点左右,我的函数都会触发一个触发器。

Every few days (I don't know why) but I get an每隔几天(我不知道为什么),但我得到一个

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

I've given up trying to solve that issue, but it would be great if at the end of my function I could include some code to check if there was an execution error and if so run another function eg我已经放弃尝试解决这个问题,但是如果在我的 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();
    }
}

Error handling in Apps Script can be handled by both JavaScript and Apps Script troubleshooting tools. 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);
} 
}

Error handling function:错误处理 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);
}

The letter e in the parenthesis is an "exception object" that contains a JavaScript error message, and the "stack."括号中的字母e是一个“异常对象”,其中包含 JavaScript 错误消息和“堆栈”。 If the catch block runs code, then the execution failed.如果 catch 块运行代码,则执行失败。 You don't need to test for whether it failed or not.您无需测试它是否失败。 To get the error message use e.message and to get the stack use e.stack .要获取错误消息,请使用e.message并获取堆栈使用e.stack

You may wish to send error information to Apps Script StackDriver service and/or handle the error through your own code.您可能希望将错误信息发送到 Apps Script StackDriver 服务和/或通过您自己的代码处理错误。

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

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