score:25

Accepted 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' });

score:0

you could try with the cause propoty of :

ts has inaccurate value type about it at present, this is being discussed on the official to revolve it.

try {
     throw new error('email already exists', { 
       cause: { status: 400 } 
     });
   } catch(e) {
     console.log(e); // error('email already exists')
     console.log(e.cause) // { status: 400 }
   }

or throw the error instance with the custom property

try {
     const error = new error('email already exists');
     error.status = 400;
     throw error;
   } catch(e) {
     console.log(e); // error('email already exists')
     console.log(e.status) // 400
}
  

score:1

https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/error

the error object takes a string parameter as the first parameter.

json.stringify the object if you are looking to print it out to the console.

throw new error(json.stringify({ status: 400, error: 'email already exists' }));

you will get something like this: uncaught error: {"status":400,"error":"email already exists"}

https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/json/stringify


Related Query

More Query from same tag