尝试...捕获在 Google Apps 脚本中未按预期工作

Kar*_*iam 4 javascript validation try-catch google-sheets google-apps-script

[编辑以包含TJ Crowder建议的最小可重现示例。]

我正在使用 Google Apps 脚本开发一个简单的函数,该函数应该将日期错误字符串发布到电子表格的列中。该列已具有拒绝任何非有效日期值的数据验证规则。这一切都很好。

我的问题是这样的:

我尝试使用 try...catch 块来优雅地处理错误,并在值未通过数据验证时仅记录错误消息。try...catch 似乎根本不起作用。相反,脚本会抛出错误并中断,并且日志显示为空。

这是带有新代码的更新屏幕截图(抱歉,Sourabh Choraria,覆盖了您的更新)。令人惊讶的是,GAS 突出显示了错误发生位置上方的一行。

更新后的代码的屏幕截图

作为一点背景知识,此脚本获取存储在列中的各种其他电子表格的 ID,获取每个电子表格的最后更新时间戳,并将结果发布到结果列中。

这是我使用的代码。

function trackDocUpdates() {
    //Set the global variables
    var ss = SpreadsheetApp.getActive();
    var residentSheet = ss.getSheetByName("Resident Documents");
    var activeRange = residentSheet.getDataRange();
    var numRows = activeRange.getNumRows();
    var lastRevision = "No value yet.";

    //Loop through the rows of data to get the last updated timestamp of each document
    //The first data row is the 5th row of the sheet currently, hence the for loop starts at 5
    for (i = 5; i <= numRows; i++) {
        //Get the document URL from the current row. Currently the second column has the document URLs
        var docURL = residentSheet.getRange(i, 2).getValue();
        //Extract the document's ID from the URL
            var docId = docURL.split("/")[5];
            //As long as there's a valid-looking document ID, get the last updated timestamp for the current document in the loop
            if (docId != undefined) {
                lastRevision = getLastRevision(docId);
                Logger.log(lastRevision);
            }

            else {
                lastRevision = "No document URL found";
                Logger.log(lastRevision);
            }
        //Post the last updated timestamp in the appropriate result cell
        postLastUpdatedTime(lastRevision, i, 9);
    }

    //Function to get the last updated timestamp for a given document
    function getLastRevision(docId) {
        //Try to get the last updated timestamp for the given document ID
        try {
            var revisions = Drive.Revisions.list(docId);
            if (revisions.items && revisions.items.length > 0) {
                var revision = revisions.items[revisions.items.length-1];
                var lastModified = new Date(revision.modifiedDate);
                //var modifiedDateString = Utilities.formatDate(lastModified, ss.getSpreadsheetTimeZone(), "MMM dd, yyyy hh:mm:ss a");
                return lastModified;
            }

            else {
                return 'No revisions found.';
            }
        }
        //If the file cannot be accessed for some reason (wrong docId, lack of permissions, etc.), return an appropriate message for posting in the result cell
        catch(err) {
            return "File cannot be accessed.";
        }

    }

    //Function to post the last updated timestamp for a given document in the given result cell
    function postLastUpdatedTime(message, rowIndex, colIndex) {
        //If there's no argument is passed to colIndex, set its value to be 11
        colIndex = colIndex || 11;
        var cellToPost = residentSheet.getRange(rowIndex, colIndex);
        try {
            cellToPost.setValue(message);
            cellToPost.setNumberFormat('MMM dd, yyyy hh:mm:ss AM/PM');
        }

        catch(err) {
            Logger.log(err);
            residentSheet.getRange(rowIndex, 12).setValue(err);
        }

    }

    //Update the last refreshed time of the script in the first row of the result column
    var scriptUpdatedTime = new Date();
    postLastUpdatedTime(scriptUpdatedTime, 1);
}
Run Code Online (Sandbox Code Playgroud)

谁能帮助我理解我哪里出错了?

PS:我无权删除最初提出此问题的数据验证,因为我只是向客户现有的电子表格添加功能。

And*_*rte 5

我能够重现你的问题。

这个确切的问题已报告给 Google (issuetracker.google.com),并且他们提交了一份内部案例 [1],内容涉及 Apps 脚本中的 try/catch 语句不处理数据验证错误。

[1] https://issuetracker.google.com/issues/36763134#comment7

  • 非常感谢。至少现在我不必到处寻找技术上不存在的解决方案。了解 Google Apps 脚本引擎不会将电子表格错误解释为脚本中的正确异常会有所帮助。谷歌已经就此提起内部诉讼,这一事实给人们带来了一些希望,但已经过去四年了。无论如何,我希望这可以帮助有类似问题的人理解这个缺点,并相应地编写他们的 GAS 脚本。 (2认同)