Skip to content
Advertisement

Pass an object with JS throw new Error in node

I want to throw an error in my node application as follows.

JavaScript

this give me the following output.

JavaScript

I can’t access the properties of this error object. What am I doing wrong here?

Advertisement

Answer

The constructor for an Error object expects a string, not an object (which is why your scheme doesn’t work).

You are free to add your own custom properties to the Error object after you create it.

JavaScript

The standard properties on an error object are (for some reason I don’t know) not enumerable so they don’t show up in some contexts (even though they are there). Any new properties you add with plain assignment like above, will be enumerable.

FYI, you do this in multiple places, you can also subclass the Error object and give your subclass a constructor that takes whatever arguments you want to give it. That constructor can then call super(msg) and then add its own properties to the error object from the constructor arguments.

The [object Object] is your message is because you are attempting to convert your error object to a string and the default string representation of the object is [object Object]. That will happen if you trying to use your error object in a string such as:

JavaScript

Instead, you should pass the whole object to console.log() like this:

JavaScript

And, the console.log() gets the whole object and can display its properties.


You can also make your own error subclass that then takes whatever constructor arguments you want. So, if you want to pass an object to your custom error object, you can do that like this:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement