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

前端 未结 7 1193
面向向阳花
面向向阳花 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:58

    You can use Error.captureStackTrace for filtering out unneeded line in stack trace.

    function MyError() {
        var tmp = Error.apply(this, arguments);
        tmp.name = this.name = 'MyError';
    
        this.message = tmp.message;
        /*this.stack = */Object.defineProperty(this, 'stack', { // getter for more optimizy goodness
            get: function() {
                return tmp.stack;
            }
        });
    
        Error.captureStackTrace(this, MyError); // showing stack trace up to instantiation of Error excluding it.
    
        return this;
     }
     var IntermediateInheritor = function() {},
         IntermediateInheritor.prototype = Error.prototype;
     MyError.prototype = new IntermediateInheritor();
    
     var myError = new MyError("message");
     console.log("The message is: '"+myError.message+"'"); // The message is: 'message'
     console.log(myError instanceof Error);                // true
     console.log(myError instanceof MyError);              // true
     console.log(myError.toString());                      // MyError: message
     console.log(myError.stack);                           // MyError: message \n 
                                                      // <stack trace ...>
    
    0 讨论(0)
提交回复
热议问题