I want to throw an error in my node application as follows.
throw new Error({ status: 400, error: 'Email already exists' });
this give me the following output.
Error: [object Object]
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.
let err = new Error('Email already exists'); err.status = 400; err.whateverElse = someValue; throw err;
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:
console.log('Error: ' + err);
Instead, you should pass the whole object to console.log()
like this:
console.log('Error:', err);
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:
class MyError extends Error { constructor(data) { super(data.message); this.status = data.status; } } throw new MyError({ status: 400, message: 'Email already exists' });