Alex Alex - 6 months ago 12
Node.js Question

nodejs new Error(message) and Object.keys()

const err = new Error('invalid');
err.code = 200;
console.log(Object.keys(err));


=>

[ 'code' ]


Why isn't
message
, or
stack
a key of
err
?

Isn't
Error
an ES6 Class?

What is the implementation of
err.getAllProperties()
so that it returns
code
as well as its 'hidden' properties like
message
and
stack
?

Answer

Instead of:

Object.keys(err).forEach(function(key) {
  var val = err[key];
  console.log(val);
});

use

Object.getOwnPropertyNames(err).forEach(function (key) {
  var val = err[key];
  console.log(val);
});

Output:

This is stack info

This is an error message

200

More information on Object.getOwnPropertyNames.

Comments