Search code examples
javascriptprototype

How can I get an javascript error's prototype member object keys?


How can I get an javascript error's prototype member object keys?

I run into this question when I catch an error, I don't know if the console output behave this way because of something special about the Error class/type/....

try {
  throw new Error('sample error')
} catch (ex) {
  console.log(ex instanceof Error)
  //true

  console.log(ex.message)
  //sample error

  console.log(Object.keys(ex))
  //[] fine as i suppose the class/type members exist in prototype

  console.log(ex.__proto__)
  //{name:'error', message:'', constructor:.... i suppose these are the default properties of Error

  console.log(Object.keys(ex.__proto__))
  //[] how come empty array still??? 
}

I suppose it the last statement console.log(Object.keys(ex.__proto__)) should return ['name', 'message'...]. Just wonder what I did wrong.


Solution

  • Object.getOwnPropertyDescriptor(ex.__proto__, "name")
    # => {value: "Error", writable: true, enumerable: false, configurable: true}
    

    The non-enumerable properties don't show up in Object.keys.