Preface
The answer provides a guide on general errors that can be encountered when working with any Google service (both built-in and advanced) or API. For errors specific to certain services, see the other answer.
Back to reference
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 a variable is a special data type undefined
. Typically, the error occurs when accessing nested properties of an object.
A variation of this error with a 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
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])
.
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
- Parsing order of the 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. A common mistake that causes the error is 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.
The 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).
A 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
- Context mismatch is easily fixed by changing the service on which the method is called.
- 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:
- Setting up type guards (
typeof myVar === "string"
and similar).
- 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");
})()