I noticed a strange behavior while defining custom error objects in Javascript:
function MyError(msg) {
Error.call(this, msg);
this.name = \"MyError\
Another approach to this is to make the new error instance the prototype of this
, and that way you don't have to know what properties to copy, which gets around the problems B T talked about at the end of their answer.
function MyError() {
if (this === undefined) {
throw TypeError("MyError must be called as a constructor");
}
let newErr = Error.apply(undefined, arguments);
Object.setPrototypeOf(newErr, MyError.prototype);
Object.setPrototypeOf(this, newErr);
}
MyError.prototype = Object.create(Error.prototype);
let me = new MyError("A terrible thing happened");
console.log(me instanceof MyError); // true
console.log(me instanceof Error); // true
console.log(me.message); // A terrible thing happened
And for my money it's a bit neater. But note that Object.setPrototypeOf() (or object.__proto__ =
on non ES6 compliant implementations that support it) can be very slow, so if you are using these errors on your golden paths then you may not want to do this.