Inheriting from the Error object - where is the message property?

前端 未结 7 1214
面向向阳花
面向向阳花 2020-11-30 02:58

I noticed a strange behavior while defining custom error objects in Javascript:

function MyError(msg) {
    Error.call(this, msg);
    this.name = \"MyError\         


        
7条回答
  •  一生所求
    2020-11-30 03:37

    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.

提交回复
热议问题