Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I see the keys of an Error object?

I am mystified by the fact that when I create a new Error object I can see its message or name, but I can't see a list of its keys by using the standard ways. Why is that?

> err = new Error("an error") [Error: an error] > err.message 'an error' > err.name 'Error' > Object.keys(err) [] > JSON.stringify(err) '{}' 
like image 553
Selah Avatar asked Aug 16 '13 16:08

Selah


People also ask

How can you tell if an object has a certain key?

How to Check if an Object Has a key in JavaScript with the in Operator. You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain.

Why is object property undefined JavaScript?

Undefined value primitive value is used when a variable has not been assigned a value. The standard clearly defines that you will receive undefined when accessing uninitialized variables, non-existing object properties, non-existing array elements, and alike.


1 Answers

JavaScript properties may be non-enumerable, which means they does not appear in for..in loops or Object.keys results.

You can use Object.getOwnPropertyNames to get all properties (enumerable or non-enumerable) directly on an object. I say "directly" because normal enumeration looks up the object's prototype chain to get enumerable properties on parent prototypes, while getOwnPropertyNames does not.

Thus, Object.getOwnPropertyNames(err) only shows

['stack',  'arguments',  'type',  'message'] 

The name property is a non-enumerable property of Error.prototype and is never set directly on an Error instance. (Prototyping recap: when you try to access err.name, the lookup err turns up nothing, so the interpreter looks at Error.prototype, which does have a name property.)

like image 148
apsillers Avatar answered Sep 22 '22 11:09

apsillers