基于时间的触发器捕获失败(Google Script)

时间:2015-06-22 13:41:15

标签: google-apps-script

我有一个监视某个文件夹子集的脚本。它记录子集中的所有文件及其上次编辑日期和位置。然后,它会发送一封包含最近编辑过的所有文件的电子邮件,以及一封单独的电子邮件,其中包含3个多月未触及的所有文件。这是为了让我们公司的经理能够了解这些文件夹中发生的事情。

问题:此脚本每周一上午5点运行。大约每隔一周,我就会在“sheet.appendRow(data)”这一行上收到“服务错误:Spreadsheets”。

如果我然后进入并手动运行它,它可以正常工作。

有没有办法捕获错误并重新运行直到成功?

编辑:代码

    function listFilesInFolderNew() {
      var start = new Date().getTime();
      var parentFolder = getParentFolder();
      var parentFolderID = DriveApp.getFolderById(getParentFolderID());
      var level1Folders = parentFolderID.getFolders();
      var level1Files = parentFolderID.getFiles();
      var file;
      var allFolders;
      var subFolders;
      var subFileList;
      var data;
      var level2Files;
      var level2Folders;
      var level3Files;
      var level3Folders;
      var level4Files;
      var level4Folders;
      var folderArray;
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName("Log");
      sheet.clear();
      sheet.appendRow(["Name", "Date Created", "URL", "Last Updated",
                       "Parent Folder", "Last Updated By"
                      ]);
      // Every file in the folder containing this file.  
      // Level 1 ----------------- Files in Level 1
      var parentName = "";
      while (level1Files.hasNext()) {
        var level1File = level1Files.next();
        parentName = "";
        try {
          parentName = level1File.getParents()[0].getName();
        } catch (err) {}
        if (parentFolder != "Terminated Files") {
          data = [
            level1File.getName(), level1File.getDateCreated(),
            level1File.getUrl(), level1File.getLastUpdated(),
            parentFolder, Drive.Files.get(level1File.getId()).lastModifyingUser
            .displayName
          ];
          sheet.appendRow(data);
        }
      }
      // Level 1 ----------------- Folders in Level 1
      while (level1Folders.hasNext()) {
        var level1Folder = level1Folders.next();
        level2Folders = level1Folder.getFolders();
        level2Files = level1Folder.getFiles();
        // Level 2 ----------------- Folders in Level 2  
        while (level2Folders.hasNext()) {
          var level2Folder = level2Folders.next();
          level3Folders = level2Folder.getFolders();
          level3Files = level2Folder.getFiles();
          // Level 3 ----------------- Folders in Level 3  
          while (level3Folders.hasNext()) {
            var level3Folder = level3Folders.next();
            level4Folders = level3Folder.getFolders();
            level4Files = level3Folder.getFiles();
            // Level 4 ----------------- Files in Level 4  
            while (level4Files.hasNext()) {
              var level4File = level4Files.next();
              folderArray = [];
              parentName = level4File.getParents().next();
              try {
                while (parentName.getName() != "My Drive") {
                  folderArray.push(parentName.getName());
                  parentName = parentName.getParents().next();
                }
              } catch (err) {}
              if (folderArray[0] != "Terminated Files") {
                data = [
                  level4File.getName(), level4File.getDateCreated(),
                  level4File.getUrl(), level4File.getLastUpdated(),
                  folderArray[0], Drive.Files.get(level4File.getId())
                  .lastModifyingUser.displayName
                ];
                sheet.appendRow(data);
              }
            }
          }
          // Level 3 ----------------- Files in Level 3  
          while (level3Files.hasNext()) {
            var level3File = level3Files.next();
            folderArray = [];
            parentName = level3File.getParents().next();
            try {
              while (parentName.getName() != "My Drive") {
                folderArray.push(parentName.getName());
                parentName = parentName.getParents().next();
              }
            } catch (err) {}
            if (folderArray[0] != "Terminated Files") {
              data = [
                level3File.getName(), level3File.getDateCreated(),
                level3File.getUrl(), level3File.getLastUpdated(),
                folderArray[0], Drive.Files.get(level3File.getId())
                .lastModifyingUser.displayName
              ];
              sheet.appendRow(data);
            }
          }
        }
        // Level 2 ----------------- Files in Level 2  
        while (level2Files.hasNext()) {
          var level2File = level2Files.next();
          folderArray = [];
          parentName = level2File.getParents().next();
          try {
            while (parentName.getName() != "My Drive") {
              folderArray.push(parentName.getName());
              parentName = parentName.getParents().next();
            }
          } catch (err) {}
          if (folderArray[0] != "Terminated Files") {
            data = [
              level2File.getName(), level2File.getDateCreated(),
              level2File.getUrl(), level2File.getLastUpdated(),
              folderArray[0], Drive.Files.get(level2File.getId())
              .lastModifyingUser.displayName
            ];
            sheet.appendRow(data);
          }
        }
      }
      getAndSendEmails();
      var stop = new Date().getTime();
      var total = stop - start;
      total = total / 1000; //seconds
      total = total / 60; //minutes
      Logger.log("Start: " + start + "; Stop: " + stop + "; Total: " + total);
    }

    function getAndSendEmails() {
      //Get Emails
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName("Log");
      var Emails = "";
      var emailSheet = ss.getSheetByName("Notifications");
      var dataRange = emailSheet.getRange("A2:A10");
      var dataEmail = dataRange.getValues();
      for (var i = 0; i < dataEmail.length; ++i) {
        var row = dataEmail[i];
        var emailAddress = row[0]; // First column
        Emails = Emails + " " + emailAddress + ", ";
      }
      var timeCreated;
      var timeEdited;
      var d = new Date();
      var oneWeekAgo = new Date();
      oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
      var days90Ago = new Date();
      days90Ago.setDate(days90Ago.getDate() - 90);
      var changes =
          "<b>Recent Documents: (edited/created in last week) </b> <br><table><tr><td style=\"border-bottom:1px solid #000;\"><b>Document/Link</b></td><td style=\" border-bottom:1px solid #000;\"><b>Date Edited Last</b></td><td style=\" border-bottom:1px solid #000;\"><b>Last Edited By</b></td><td style=\" border-bottom:1px solid #000;\"><b>Manager / Containing Folder</b></td></tr>";
      var changesNOCHANGE =
          "<b>Recent Documents: (edited/created in last week) </b> <br><table><tr><td style=\"border-bottom:1px solid #000;\"><b>Document/Link</b></td><td style=\" border-bottom:1px solid #000;\"><b>Date Edited Last</b></td><td style=\" border-bottom:1px solid #000;\"><b>Last Edited By</b></td><td style=\" border-bottom:1px solid #000;\"><b>Manager / Containing Folder</b></td></tr>";
      var stale =
          "<br><b>Stale Documents: (90+ days since edit)</b> <br><table><tr><td style=\" border-bottom:1px solid #000;\"><b>Document/Link</b></td><td style=\" border-bottom:1px solid #000;\"><b>Date Edited Last</b></td><td style=\" border-bottom:1px solid #000;\"><b>Last Edited By</b></td><td style=\" border-bottom:1px solid #000;\"><b>Manager / Containing Folder</b></td></tr>";
      var staleNOCHANGE =
          "<br><b>Stale Documents: (90+ days since edit)</b> <br><table><tr><td style=\" border-bottom:1px solid #000;\"><b>Document/Link</b></td><td style=\" border-bottom:1px solid #000;\"><b>Date Edited Last</b></td><td style=\" border-bottom:1px solid #000;\"><b>Last Edited By</b></td><td style=\" border-bottom:1px solid #000;\"><b>Manager / Containing Folder</b></td></tr>";
      timeCreated = sheet.getRange("B2:B").getValues();
      timeEdited = sheet.getRange("D2:D").getValues();
      var lastEditedBy = sheet.getRange("F2:F").getValues();
      var shortOneWeekAgo = oneWeekAgo.toString().substring(0, 15);
      var shortDays90Ago = days90Ago.toString().substring(0, 15);
      var timeCreatedValue;
      var timeEditedValue;
      var shortCreated;
      var shortEdited;
      var dateEditedString;
      // If file is edited or created in the last week, send email.
      for (var j = 2; j < sheet.getLastRow() + 1; j++) {
        timeCreatedValue = timeCreated[j - 2];
        timeEditedValue = new Date(timeEdited[j - 2]);
        shortCreated = timeCreatedValue.toString().substring(0, 15);
        shortEdited = timeEditedValue.toString().substring(0, 15);
        dateEditedString = timeEditedValue.toString();
        //    Logger.log("\n" + timeEditedValue + " = " + "\n" + oneWeekAgo);
        //    Logger.log("\n" + shortEdited + " = " + "\n" + shortOneWeekAgo);    
        if (timeCreatedValue >= oneWeekAgo || timeEditedValue >= oneWeekAgo) {
          changes = changes +
            "<tr> <td style=\" border-bottom:1px solid #000;\"><a href=" +
              "\"" + sheet.getRange("C" + j).getValue() + "\"" + "> " +
                sheet.getRange("A" + j).getValue() + "</a></td>" +
                  "<td style=\" border-bottom:1px solid #000;\">" +
                    dateEditedString.substring(0, 24) + "</td>" +
                      "<td style=\" border-bottom:1px solid #000;\">" +
                        lastEditedBy + "</td>" +
                          "<td style=\" border-bottom:1px solid #000;\">" + sheet.getRange(
                            "E" + j).getValue() + "</tr>";
        }
    //    if (timeEditedValue <= days90Ago) {
    //      Logger.log(timeEditedValue + " <= " + days90Ago);
    //    } else {
    //      Logger.log(timeEditedValue + " is not <= " + days90Ago);
    //    }
        if (timeEditedValue <= days90Ago) {
          dateEditedString = timeEditedValue.toString();
          stale = stale +
            "<tr> <td style=\" border-bottom:1px solid #000;\"><a href=" +
              "\"" + sheet.getRange("C" + j).getValue() + "\"" + "> " +
                sheet.getRange("A" + j).getValue() + "</a></td>" +
                  "<td style=\" border-bottom:1px solid #000;\">" +
                    dateEditedString.substring(0, 24) + "</td>" +
                      "<td style=\" border-bottom:1px solid #000;\">" +
                        lastEditedBy + "</td>" +
                          "<td style=\" border-bottom:1px solid #000;\">" + sheet.getRange(
                            "E" + j).getValue() + "</tr>";
        }
      }
      changes = changes + "</table>";
      changesNOCHANGE = changesNOCHANGE + "</table>";
      stale = stale + "</table>";
      staleNOCHANGE = staleNOCHANGE + "</table>";
      if (changes != changesNOCHANGE) {
        MailApp.sendEmail({
          to: Emails,
          bcc: "my.email***",
          subject: "Weekly Log of Recent Documents in Folder",
          htmlBody: changes,
          name: "Folder Weekly Status"
        });
      }
      if (stale != staleNOCHANGE) {
        MailApp.sendEmail({
          to: Emails,
          bcc: "my.email***",
          subject: "Weekly Log of Stale Documents in Folder",
          htmlBody: stale,
          name: "Folder Weekly Status"
        });
      }
    }

    function getParentFolder() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var SSID = ss.getId();
      var fileInDrive = DriveApp.getFolderById(SSID);
      var folderinDrive = fileInDrive.getParents().next().getName();
      return folderinDrive;
    }

    function getParentFolderID() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var SSID = ss.getId();
      var fileInDrive = DriveApp.getFolderById(SSID);
      var folderinDrive = fileInDrive.getParents().next().getId();
      return folderinDrive;
    }
    //function addMinutes(date, minutes) {
    //  return new Date(date.getTime() + minutes*60000);
    //}

1 个答案:

答案 0 :(得分:1)

这些失败确实经常发生,通常不是由于编码问题。

最好不要无限制地尝试,但如果你给自己预算说n次,那么简单的模式可能就是......

var success, count = 0;
do {
    try {

        // whatever statement or block subject to the try
        sheet.appendRow(data);

        // last statement should confirm success
        success = true;

    } catch (err) {
        // Log error perhaps
    }
    count += 1;
} while (!success && count < 10);

很可能你得到的失败可能比这种模式可以处理的时间更长,作为替代方案,catch(err)块可能会在几分钟后添加另一个可安装的一次性触发器。