1

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)

Vinay
  • 33
  • 3

2 Answers2

4

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);
  }
}
jmrk
  • 34,271
  • 7
  • 59
  • 74
3

You might have been expecting the properties that were previously present in Errors, Error.fileName and Error.lineNumber are no longer supported in V8. There is instead Error.prototype.stack. which would not show up under the iterable properties of Error.

To iterate over the Error prototype properties, you can follow the code in this answer: List Down All Prototype Properties of an Javascript Object

The changes to the Error object are mentioned in this section of their V8 migration guide.

In the V8 runtime, the standard JavaScript Error object doesn't support the fileName or lineNumber as constructor parameters or object properties.

When migrating your script to V8, remove any dependence on Error.fileName and Error.lineNumber.

An alternative is to use the Error.prototype.stack. This stack is also non-standard, but supported in both Rhino and V8.

muds
  • 518
  • 1
  • 3
  • 13