1

I've looked around and have failed to find an answer to this.

What I am trying to do is print all the properties available in an Error object for error reporting. It may be impossible, but I would at least like to know why.

I have tried the following in Chrome and Firefox on Ubuntu 12.04.

try {
   throw new Error('Foo');
} catch (x) {
   console.log(Object.keys(x)); // []
   for (var i in x) console.log(i); // Prints nothing
}
3
  • Why not simply use console.dir(x); to see what's inside (mostly the stack function) ? Commented May 12, 2014 at 14:04
  • What's the goal ? Are you adding properties ? Commented May 12, 2014 at 14:05
  • No. I need something to send back to the server for error reporting. Commented May 12, 2014 at 14:06

1 Answer 1

5

The enumerability of Error object keys varies amongst browsers. Your best bet is to use Object.getOwnPropertyNames:

var props = Object.getOwnPropertyNames(x);
console.log(props);
for (var i=0; i<props.length; i++) console.log(x[props[i]]);

I need something to send back to the server for error reporting.

I'd go with explicitly naming the properties I'm interested in, for example:

reportErrorBack( JSON.stringify({
    name: e.name, // on the Error.prototype
    message: e.message,
    stack: e.stacktrace
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. Do you know why you can't Enumerate over Error objects?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.