I am trying to get the stack trace (and other details) when an exception occurs in my code. To do this the following piece of code use to work:
function catchException() {
var errLog = [];
try {
var temp;
temp.split(",");
} catch (exception) {
for (var property in exception) {
errLog.push(property + ": " + exception[property]);
}
}
return errLog;
}
But ever since the v8 runtime update on Google Apps Script, this doesn't return any property of the exception object.
In v8 runtime, I can get the stack trace in the above code, if I use exception["stack"]
, I get the stack trace.
But I was hoping I could avoid using the string ("stack"
) and also get all the other properties of the exception for which I might not know the property name.
The for...in
loop doesn't seem to be working in this scenario.
How can I access the exception object's properties?
(all the properties without using the property names)
for..in
only enumerates properties that are configured as enumerable; an exception's "stack" property is not enumerable (you can check with Object.getOwnPropertyDescriptor(exception, "stack")
). You can use Object.getOwnPropertyNames
to get all property names of an object, enumerable or not:
let keys = Object.getOwnPropertyNames(exception);
for (let key of keys) {
console.log(key + ": " + exception[key]);
}
Note that, as the name implies, this lists an object's own properties. If you're also interested in properties inherited from its prototypes, you can use a loop to iterate the prototype chain:
function DumpAllProperties(o) {
let receiver = o;
while (o) {
for (let key of Object.getOwnPropertyNames(o)) {
console.log(key + " -> " + receiver[key]);
}
o = Object.getPrototypeOf(o);
}
}