如何解决Google Apps脚本开发中的常见错误 [英] How to solve common errors in Google Apps Script development

查看:134
本文介绍了如何解决Google Apps脚本开发中的常见错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题与解答(Q& A)当前是标签.

在其他语言和通用标签中也有类似的成功案例(请参阅 android php ,再次 php ),然后再执行此操作西装.


为什么存在?

无论是新手还是经验丰富的开发人员,对于在开发和生产过程中遇到的错误的含义和解决方案,可以有效地减少为一个答案的问题的数量是巨大的.在撰写本文时,即使仅通过语言标签运行查询也会产生以下结果:

由于需要考虑细微差别和措辞不佳的标题,因此链接至最相关的副本对于志愿者而言既困难又费时.


它由什么组成?

此问答包含的条目旨在提供有关如何进行操作的信息:

  • 解析错误消息结构
  • 了解错误的含义
  • 一致地复制(如果适用)
  • 解决问题
  • 在可能的情况下提供指向规范问答的链接

这不是什么吗?

Q& A的范围仅限于 common (不平凡).这不是:

  • 全面指南或最佳做法"收藏
  • 有关ECMAScript一般错误的参考
  • GAS文档
  • 资源列表(为此,我们有一个标签Wiki )

要添加什么?

添加条目时,请考虑以下事项:

  • 该错误是否足够常见(示例,请参见为什么"部分)?
  • 解决方案能否简明扼要地描述并适用于大多数情况?

解决方案

前言

初始答案提供了有关常规内置与服务中相关的错误.
解决与服务有关的条目列在官方中参考.

这是一个正在进行的项目,并将不断更新.


常规错误


消息

TypeError:无法从undefined (or null)

读取属性'property name here'

说明

错误消息表明您正在尝试访问Object实例上的属性,但是在运行时期间,变量持有的 actually 值是一种特殊的数据类型undefined.通常,访问对象的嵌套属性时会发生错误.

此错误的变化形式是使用数字值代替属性名称,表明需要Array的实例.由于JavaScript中的数组是对象,所以一切这里提到的对他们也是正确的.

动态构造对象有一种特殊情况,例如 TypeError 因为应该是"object",但是会收到"undefined"

如何修复

  1. 使用默认值
    JavaScript中的逻辑或 ||运算符如果左侧是 falsy,则具有评估右侧的有趣属性.由于JS中的对象是真实的,而undefinednull是虚假的,因此像(myVar || {}).myProp [用于数组的(myVar || [])[index]]这样的表达式将保证不会引发错误,并且该属性至少为undefined.

    还可以提供默认值:(myVar || { myProp : 2 })保证默认情况下访问myProp返回2.数组也是如此:(myVar || [1,2,3]).

  2. 检查类型
    对于特殊情况尤其如此,typeof operator if 声明比较运算符将允许函数在其指定的上下文之外运行(即出于调试目的),或者根据对象是否存在而引入分支逻辑.

    一个人可以控制检查的严格程度:

    • 宽松("not undefined"):if(typeof myVar !== "undefined") { //do something; }
    • 严格(仅适用对象"):if(typeof myVar === "object" && myVar) { //do stuff }

相关的问答集

    GAS项目的
  1. 解析顺序问题


消息

无法将some value转换为data type

说明

由于传递了比方法期望的不同类型的参数而引发错误.导致该错误的常见错误是的意外强制>字符串编号.

如何复制

function testConversionError() {
  const ss = SpreadsheetApp.getActiveSheet();
  ss.getRange("42.0",1);
}

如何修复

确保错误消息中引用的值是文档所要求的数据类型,并且容器绑定脚本. 导致错误的主要用例是尝试调用仅在一种文档类型中可用的方法(通常是getUi(),因为它是 自定义函数(通常由带有特殊JSDoc样式的注释@customfunction标记并用作公式的函数)调用.

如何复制

对于绑定脚本上下文不匹配的情况,请在与Google表格(或Google Docs以外的其他产品)相关联的脚本项目中声明并运行此函数:

function testContextMismatch() {
  const doc = DocumentApp.getUi();
}

请注意,调用DocumentApp.getActiveDocument()只会导致null不匹配,并且执行将成功.

对于自定义函数,请在任何单元格中将以下声明的函数用作公式:

/**
 * @customfunction
 */
function testConversionError() {
  const ui = SpreadsheetApp.getUi();
  ui.alert(`UI is out of scope of custom function`);
}

如何修复

  1. 通过更改调用该方法的服务,可以轻松解决上下文不匹配的问题.
  2. 无法使自定义函数 调用这些服务,请使用自定义菜单或对话框.


消息

找不到方法Method name here

参数param namesmethod name

的方法签名不匹配

说明

对于新手来说,此错误有一条令人困惑的消息.它的意思是在调用有问题的方法时传递的一个或多个参数中发生了类型不匹配.

没有一种方法具有与您的调用方式相对应的签名.找不到"

如何修复

这里唯一的解决方法是仔细阅读文档,并检查订单和推断出的参数类型是正确的(使用具有自动完成功能的良好IDE会有所帮助).但是,有时会发生此问题,因为一个人希望该值属于某种类型,而在运行时中则是另一个.有一些防止此类问题的提示:

  1. 设置类型防护(typeof myVar === "string"等).
  2. 由于JavaScript为

     /**
     * @summary pure arg validator boilerplate
     * @param {function (any) : any}
     * @param {...any} args
     * @returns {any[]}
     */
    const validate = (guard, ...args) => args.map(guard);
    
    const functionWithValidator = (...args) => {
      const guard = (arg) => typeof arg !== "number" ? parseInt(arg) : arg;
    
      const [a,b,c] = validate(guard, ...args);
      
      const asObject = { a, b, c };
      
      console.log(asObject);
      
      return asObject;
    };
    
    //driver IIFE
    (() => {
      functionWithValidator("1 apple",2,"0x5");
    })() 


消息

您无权执行该操作

该脚本无权执行该操作

说明

该错误表明所访问的API或服务之一缺少用户的足够权限.在其文档中具有 authorization 部分的每种服务方法都至少需要对一个范围进行授权.

由于GAS实质上是为了开发方便而围绕Google API,因此OAuth 2.0 API范围中列出的大多数范围参考,尽管如果在相应文档中列出了参考,则最好使用它,因为存在一些不一致之处.

请注意,自定义功能在未经授权的情况下运行.从Google表格单元格调用函数是导致此错误的最常见原因.

如何修复

如果从脚本编辑器运行了调用服务的函数,则会自动提示您使用相关范围对其进行授权.尽管对于快速的手动测试很有用,但最佳实践是明确设置范围在应用程序清单(appscript.json)中.此外,自动范围通常太宽泛,以至于无法通过审查打算发布该应用.

清单文件(如果在代码编辑器中为View -> Show manifest file)中的字段oauthScopes应该看起来像这样:

  "oauthScopes": [
    "https://www.googleapis.com/auth/script.container.ui",
    "https://www.googleapis.com/auth/userinfo.email",
    //etc
  ]

对于自定义功能,您可以通过切换为从菜单或按钮因为无法授权自定义功能.

对于正在开发编辑器加载项的用户此错误表示未处理的授权生命周期模式:在身份验证模式为AuthMode.NONE的情况下,在调用需要授权的服务之前必须中止.

相关原因和解决方案

  1. @OnlyCurrentDoc 限制脚本访问范围
  2. 范围自动检测


消息

ReferenceError:service name未定义

说明

最常见的原因是使用高级服务而未启用它.启用此类服务​​后,指定标识符下的变量将附加到全局范围供开发人员直接参考.因此,当引用禁用的服务时,将抛出ReferenceError.

如何修复

转到资源->高级Google服务"菜单,然后启用引用的服务.请注意,标识符应等于引用的全局变量. 有关详细说明,请阅读官方指南.

如果未引用任何高级服务,则错误指向未声明的变量.


消息

脚本已完成,但未返回任何内容.

找不到脚本功能:doGet or doPost

说明

这本身不是错误(因为返回的HTTP响应代码为200,并且执行被标记为成功,但通常被视为执行一次.尝试从浏览器进行请求/访问时出现此消息脚本部署为网络应用.

发生这种情况的主要原因有两个:

  1. 没有doGetdoPost触发功能
  2. 上方的触发器不会返回 HtmlOutputTextOutput实例

如何修复

出于第一个原因,只需提供doGetdoPost触发器(或两者)即可.第二,确保您的应用程序的所有路由都以 TextOutput HtmlOutput :

//doGet returning HTML
function doGet(e) {
  return HtmlService.createHtmlOutput("<p>Some text</p>");
}

//doPost returning text
function doPost(e) {
  const { parameters } = e;
  const echoed = JSON.stringify(parameters);
  return ContentService.createTextOutput(echoed);
}

请注意,应该仅声明一个触发函数-将它们视为应用程序的入口点.

如果触发器依靠parameter/parameters来路由响应,请确保请求URL的结构为"baseURL/exec?query"或"baseURL/dev?query" ,其中query包含要通过的参数.

相关的问答集

  1. 在声明触发器后重新部署


消息

很抱歉,发生服务器错误.请稍等,然后重试.

说明

这是最隐秘的错误,几乎在任何服务下都可能发生(尽管DriveApp使用特别容易受到影响).该错误通常表明Google方面的问题要么在几个小时/天之内消失,要么在此过程中得到解决.

如何修复

没有一个灵丹妙药,通常除了解决问题之外,您无能为力.有关问题跟踪工具的信息,或者如果您拥有GSuite帐户,请联系支持.在此之前,您可以尝试以下常见的补救措施:

  1. 对于绑定脚本-创建新文档并复制现有文档项目和数据.
  2. 切换为使用高级Drive 服务(始终记住要首先启用它.)
  3. 可能存在runtimeVersion是否设置为"V8",如果未将其更改或删除任何综合列表,但总体而言根据经验,如果邮件符合太多" 模式,则您很可能已超出各自的配额.

    最有可能遇到的错误:

    • 服务被调用太多次:service name
    • 正在运行的脚本太多
    • 一天中使用过多计算机时间的服务
    • 此脚本的触发器太多

    如何修复

    在大多数情况下,唯一的解决方法是等待配额刷新或切换到另一个帐户(除非脚本被部署为具有以我身份运行"权限的Web应用程序,在这种情况下,所有者的配额将在所有用户之间共享.

    要引用当时的文档:

    每天的配额会在24小时窗口结束时刷新;但是,刷新的确切时间因用户而异.

    请注意,某些服务(例如MailApp)具有类似 getRemainingDailyQuota ,可以检查剩余配额.

    如果触发器数量超过最大数量,则可以通过 getProjectTriggers() (或选中我的触发器" 标签)并采取相应措施以减少数量(例如,通过使用 deleteTrigger(trigger) 摆脱掉一些.)

    相关规范问答

    1. 已超过最长执行时间" 问题
    2. 优化服务调用以减少执行时间 li>


    特定于服务的错误


    SpreadsheetApp

    消息

    数据中rows or cells的数量与范围内的rows or cells数量不匹配.数据为N,但范围为M.

    说明

    错误指向尺寸范围与值不匹配.通常,当值矩阵小于或大于范围时,使用setValues()方法会出现问题.

    如何复制

    function testOutOfRange() {
        const ss = SpreadsheetApp.getActiveSpreadsheet();
        const sh = ss.getActiveSheet();
        const rng = sh.getActiveRange();
        const vals = rng.getValues();
    
        try {
            vals.push([]);
            rng.setValues(vals);
        } catch (error) {
            const ui = SpreadsheetApp.getUi();
            ui.alert(error.message);
        }
    }
    

    如何修复

    如果通常期望使值超出范围,请实施捕获此类状态的防护措施,例如:

    const checkBounds = (rng, values) => {
        const targetRows = rng.getHeight();
        const targetCols = rng.getWidth();
    
        const { length } = values;
        const [firstRow] = values;
    
        return length === targetRows &&
            firstRow.length === targetCols;
    };
    


    消息

    范围的坐标超出了图纸的尺寸.

    说明

    该错误是两个问题之间发生冲突的结果:

    1. Range超出范围(getRange() 不会要求不存在的范围时抛出)
    2. 尝试在Range实例上调用方法,该方法引用工作表不存在的尺寸.

    如何复制

    function testOB() {
      const ss = SpreadsheetApp.getActiveSpreadsheet();
      const sh = ss.getActiveSheet();
      const rng = sh.getRange(sh.getMaxRows() + 1, 1);
      rng.insertCheckboxes();
    }
    

    如何修复

    检查该行数( getMaxRow() )和列( getMaxColumns() )都大于或等于等于传递给getRange()方法调用的参数,并相应地进行更改.


    UrlFetchApp

    消息

    提供的属性没有值:url

    说明

    该错误特定于UrlFetchApp服务,并且在使用空字符串或非字符串值调用fetchfetchAll方法时发生.

    如何复制

    const response = UrlFetchApp.fetch("", {});
    

    如何修复

    确保将包含URI(不一定有效)的字符串作为其第一个参数传递给该方法.由于其常见的根本原因是访问对象或数组上的不存在的属性,检查您的访问者返回实际值.


    参考

    1. 如何出错消息更有意义
    2. 调试自定义函数

    The Q&A is currently a subject of meta discussion - please, do participate. Current plan is to split where possible (and no canonicals exist) into separate Q&As. The answer to the question is a community wiki and the question intended to become one when the status of the Q&A itself is resolved.


    Preface

    This Q&A strives to become a collection and a reference target for common errors encountered during development in Google Apps Script language in hopes to improve long-term maintainability of tag.

    There are several similar and successful undergoings in other languages and general-purpose tags (see c++, android, php, php again), and this one follows suit.


    Why it exists?

    The amount of questions from both new and experienced developers regarding the meaning and solutions to errors encountered during development and production that can be effectively reduced to a single answer is substantial. At the time of writing, even running a query only by language tag yields:

    Linking to a most relevant duplicate is hard and time-consuming for volunteers due to the need to consider nuances and often poorly-worded titles.


    What it consists of?

    Entries in this Q&A contain are designed as to provide info on how to:

    • parse the error message structure
    • understand what the error entails
    • consistently reproduce (where applicable)
    • resolve the issue
    • provide a link to canonical Q&A (where possible)

    What this is not?

    The scope of the Q&A is limited to common (not trivial). This is not:

    • a catch-all guide or "best practices" collection
    • a reference for general ECMAScript errors
    • GAS documentation
    • a resources list (we have a tag wiki for that)

    What to add?

    When adding an entry, please, consider the following:

    • is the error common enough (see "why" section for examples)?
    • can the solution be described concisely and be applicable for most cases?

    解决方案

    Preface

    The initial answer provides a guide on general and built-in service-related errors.
    Entries addressing issues with services listed in official reference are welcome.

    This is an ongoing project and will be constantly updated.


    General errors


    Message

    TypeError: Cannot read property 'property name here' from undefined (or null)

    Description

    The error message indicates that you are trying to access a property on an Object instance, but during runtime the value actually held by variable is a special data type undefined. Typically, the error occurres when accessing nested properties of an object.

    A variation of this error with numeric value in place of property name indicates that an instance of Array was expected. As arrays in JavaScript are objects, everything mentioned here is true about them as well.

    There is a special case of dynamically constructed objects such as event objects that are only available in specific contexts like making an HTTP request to the app or invoking a function via time or event-based trigger.

    The error is a TypeError because an "object" is expected, but "undefined" is received

    How to fix

    1. Using default values
      Logical OR || operator in JavaScript has an intersting property of evaluating the right-hand side iff the left-hand is falsy. Since objects in JS are truthy, and undefined and null are falsy, an expression like (myVar || {}).myProp [(myVar || [])[index] for arrays] will guarantee that no error is thrown and the property is at least undefined.

      One can also provide default values: (myVar || { myProp : 2 }) guarantees accessing myProp to return 2 by default. Same goes for arrays: (myVar || [1,2,3]).

    2. Checking for type
      Especially true for the special case, typeof operator combined with an if statement and a comparison operator will either allow a function to run outside of its designated context (i.e. for debugging purposes) or introduce branching logic depending on whether the object is present or not.

      One can control how strict the check should be:

      • lax ("not undefined"): if(typeof myVar !== "undefined") { //do something; }
      • strict ("proper objects only"): if(typeof myVar === "object" && myVar) { //do stuff }

    Related Q&As

    1. Parsing order of GAS project as the source of the issue


    Message

    Cannot convert some value to data type

    Description

    The error is thrown due to passing an argument of different type than a method expects. Common mistake that causes the error is an accidental coercion of a number to string.

    How to reproduce

    function testConversionError() {
      const ss = SpreadsheetApp.getActiveSheet();
      ss.getRange("42.0",1);
    }
    

    How to fix

    Make sure that the value referenced in the error message is of data type required by documentation and convert as needed.


    Message

    Cannot call Service and method name from this context

    Description

    This error happens on a context mismatch and is specific to container-bound scripts. Primary use case that results in the error is trying to call a method only available in one document type (usually, getUi() as it is shared by several services) from another (i.e. DocumentApp.getUi() from a spreadsheet).

    Secondary, but also prominent case is a result of calling a service not explicitly allowed to be called from a custom function (usually a function marked by special JSDoc-style comment @customfunction and used as a formula).

    How to reproduce

    For bound script context mismatch, declare and run this function in a script project tied to Google Sheets (or anything other than Google Docs):

    function testContextMismatch() {
      const doc = DocumentApp.getUi();
    }
    

    Note that calling a DocumentApp.getActiveDocument() will simply result in null on mismatch, and the execution will succeed.

    For custom functions, use the function declared below in any cell as a formula:

    /**
     * @customfunction
     */
    function testConversionError() {
      const ui = SpreadsheetApp.getUi();
      ui.alert(`UI is out of scope of custom function`);
    }
    

    How to fix

    1. Context mismatch is easily fixed by changing the service on which the method is called.
    2. Custom functions cannot be made to call these services, use custom menus or dialogs.


    Message

    Cannot find method Method name here

    The parameters param names do not match the method signature for method name

    Description

    This error has a notoriously confusing message for newcomers. What it says is that a type mismatch occurred in one or more of the arguments passed when the method in question was called.

    There is no method with the signature that corresponds to how you called it, hence "not found"

    How to fix

    The only fix here is to read the documentation carefully and check if order and inferred type of parameters are correct (using a good IDE with autocomplete will help). Sometimes, though, the issue happens because one expects the value to be of a certain type while at runtime it is of another. There are several tips for preventing such issues:

    1. Setting up type guards (typeof myVar === "string" and similar).
    2. Adding a validator to fix the type dynamically thanks to JavaScript being dynamically typed.

    Sample

    /**
     * @summary pure arg validator boilerplate
     * @param {function (any) : any}
     * @param {...any} args
     * @returns {any[]}
     */
    const validate = (guard, ...args) => args.map(guard);
    
    const functionWithValidator = (...args) => {
      const guard = (arg) => typeof arg !== "number" ? parseInt(arg) : arg;
    
      const [a,b,c] = validate(guard, ...args);
      
      const asObject = { a, b, c };
      
      console.log(asObject);
      
      return asObject;
    };
    
    //driver IIFE
    (() => {
      functionWithValidator("1 apple",2,"0x5");
    })()


    Messages

    You do not have permission to perform that action

    The script does not have permission to perform that action

    Description

    The error indicates that one of the APIs or services accessed lacks sufficient permissions from the user. Every service method that has an authorization section in its documentation requires at least one of the scopes to be authorized.

    As GAS essentially wraps around Google APIs for development convenience, most of the scopes listed in OAuth 2.0 scopes for APIs reference can be used, although if one is listed in the corresponding docs it may be better to use it as there are some inconsistencies.

    Note that custom functions run without authorization. Calling a function from a Google sheet cell is the most common cause of this error.

    How to fix

    If a function calling the service is ran from the script editor, you are automatically prompted to authorize it with relevant scopes. Albeit useful for quick manual tests, it is best practice to set scopes explicitly in application manifest (appscript.json). Besides, automatic scopes are usually too broad to pass the review if one intends to publish the app.

    The field oauthScopes in manifest file (View -> Show manifest file if in code editor) should look something like this:

      "oauthScopes": [
        "https://www.googleapis.com/auth/script.container.ui",
        "https://www.googleapis.com/auth/userinfo.email",
        //etc
      ]
    

    For custom functions, you can fix it by switching to calling the function from a menu or a button as custom functions cannot be authorized.

    For those developing editor Add-ons this error means an unhandled authorization lifecycle mode: one has to abort before calls to services that require authorization in case auth mode is AuthMode.NONE.

    Related causes and solutions

    1. @OnlyCurrentDoc limiting script access scope
    2. Scopes autodetection


    Message

    ReferenceError: service name is not defined

    Description

    The most common cause is using an advanced service without enabling it. When such a service is enabled, a variable under the specified identifier is attached to global scope that the developer can reference directly. Thus, when a disabled service is referenced, a ReferenceError is thrown.

    How to fix

    Go to "Resources -> Advanced Google Services" menu and enable the service referenced. Note that the identifier should equal the global variable referenced. For more detailed explanation, read the official guide.

    If one hasn't referenced any advanced services then the error points to an undeclared variable being referenced.


    Message

    The script completed but did not return anything.

    Script function not found: doGet or doPost

    Description

    This is not an error per se (as the HTTP response code returned is 200 and the execution is marked as successful, but is commonly regarded as one. The message appears when trying to make a request / access from browser a script deployed as a Web App.

    There are two primary reasons why this would happen:

    1. There is no doGet or doPost trigger function
    2. Triggers above do not return an HtmlOutput or TextOutput instance

    How to fix

    For the first reason, simply provide a doGet or doPost trigger (or both) function. For the second, make sure that all routes of your app end with creation of TextOutput or HtmlOutput:

    //doGet returning HTML
    function doGet(e) {
      return HtmlService.createHtmlOutput("<p>Some text</p>");
    }
    
    //doPost returning text
    function doPost(e) {
      const { parameters } = e;
      const echoed = JSON.stringify(parameters);
      return ContentService.createTextOutput(echoed);
    }
    

    Note that there should be only one trigger function declared - treat them as entry points to your application.

    If the trigger relies on parameter / parameters to route responses, make sure that the request URL is structured as "baseURL/exec?query" or "baseURL/dev?query" where query contains parameters to pass.

    Related Q&As

    1. Redeploying after declaring triggers


    Message

    We're sorry, a server error occurred. Please wait a bit and try again.

    Description

    This one is the most cryptic errors and can occur at any point with nearly any service (although DriveApp usage is particularly susceptible to it). The error usually indicates a problem on Google's side that either goes away in a couple of hours / days or gets fixed in the process.

    How to fix

    There is no silver bullet for that one and usually there is nothing you can do apart from filing an issue on issue tracker or contacting support if you have a GSuite account. Before doing that one can try the following common remedies:

    1. For bound scripts - creating a new document and copying over the existing project and data.
    2. Switch to using an advanced Drive service (always remember to enable it first).
    3. There might be a problem with a regular expression if the error points to a line with one.

    Don't bash your head against this error - try locating affected code, file or star an issue and move on


    Syntax error without apparent issues

    This error is likely to be caused by using an ES6 syntax (for example, arrow functions) while using the deprecated V8 runtime (at the time of writing GAS platform uses V8).

    How to fix

    Open "appscript.json" manifest file and check if runtimeVersion is set to "V8", change it if not or remove any ES6 features otherwise.


    Quota-related errors

    There are several errors related to quotas imposed on service usage. Google has a comprehensive list of those, but as a general rule of thumb, if a message matches "too many" pattern, you are likely to have exceeded the respective quota.

    Most likely errors encountered:

    • Service invoked too many times: service name
    • There are too many scripts running
    • Service using too much computer time for one day
    • This script has too many triggers

    How to fix

    In most cases, the only fix is to wait until the quota is refreshed or switch to another account (unless the script is deployed as a Web App with permission to "run as me", in which case owner's quotas will be shared across all users).

    To quote documentation at the time:

    Daily quotas are refreshed at the end of a 24-hour window; the exact time of this refresh, however, varies between users.

    Note that some services such as MailApp have methods like getRemainingDailyQuota that can check the remaining quota.

    In the case of exceeding maximum number of triggers one can check how many are installed via getProjectTriggers() (or check "My triggers" tab) and act accordingly to reduce the number (for example, by using deleteTrigger(trigger) to get rid of some).

    Related canonical Q&As

    1. "Maximum execution time exceeded" problem
    2. Optimizing service calls to reduce execution time


    Service-specific errors


    SpreadsheetApp

    Message

    The number of rows or cells in the data does not match the number of rows or cells in the range. The data has N but the range has M.

    Description

    The error points to a mismatch in dimensions of range in relation to values. Usually, the issue arises when using setValues() method when the matrix of values is smaller or bigger than the range.

    How to reproduce

    function testOutOfRange() {
        const ss = SpreadsheetApp.getActiveSpreadsheet();
        const sh = ss.getActiveSheet();
        const rng = sh.getActiveRange();
        const vals = rng.getValues();
    
        try {
            vals.push([]);
            rng.setValues(vals);
        } catch (error) {
            const ui = SpreadsheetApp.getUi();
            ui.alert(error.message);
        }
    }
    

    How to fix

    If it is routinely expected for values to get out of bounds, implement a guard that catches such states, for example:

    const checkBounds = (rng, values) => {
        const targetRows = rng.getHeight();
        const targetCols = rng.getWidth();
    
        const { length } = values;
        const [firstRow] = values;
    
        return length === targetRows &&
            firstRow.length === targetCols;
    };
    


    Message

    The coordinates of the range are outside the dimensions of the sheet.

    Description

    The error is a result of collision between two issues:

    1. The Range is out of bounds (getRange() does not throw on requesting a non-existent range)
    2. Trying to call a method on a Range instance referring to a non-existent dimension of the sheet.

    How to reproduce

    function testOB() {
      const ss = SpreadsheetApp.getActiveSpreadsheet();
      const sh = ss.getActiveSheet();
      const rng = sh.getRange(sh.getMaxRows() + 1, 1);
      rng.insertCheckboxes();
    }
    

    How to fix

    Check that number of rows (getMaxRow()) and columns (getMaxColumns()) are both greater or equal to the parameters passed to getRange() method call and change them accordingly.


    UrlFetchApp

    Message

    Attribute provided with no value: url

    Description

    The error is specific to UrlFetchApp service and happens when fetch or fetchAll method gets called with an empty string or non-string value.

    How to reproduce

    const response = UrlFetchApp.fetch("", {});
    

    How to fix

    Make sure that a string containing a URI (not necessarily valid) is passed to the method as its first argument. As its common root cause is accessing a non-existent property on an object or array, check whether your accessors return an actual value.


    References

    1. How to make error messages more meaningful
    2. Debugging custom functions

    这篇关于如何解决Google Apps脚本开发中的常见错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆