簡體   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