Extending Error in Javascript with ES6 syntax & Babel

后端 未结 14 1856
你的背包
你的背包 2020-11-28 01:28

I am trying to extend Error with ES6 and Babel. It isn\'t working out.

class MyError extends Error {
  constructor(m) {
    super(m);
  }
}

var error = new          


        
14条回答
  •  醉梦人生
    2020-11-28 01:58

    Quoting

    class MyError extends Error {
      constructor(message) {
        super(message);
        this.message = message;
        this.name = 'MyError';
      }
    }
    

    There is no need for this.stack = (new Error()).stack; trick thanks to super() call.

    Although the above codes cannot output the stack trace unless this.stack = (new Error()).stack; or Error.captureStackTrace(this, this.constructor.name); is invoked in Babel. IMO, it maybe one issue in here.

    Actually, the stack trace can be output under Chrome console and Node.js v4.2.1 with this code snippets.

    class MyError extends Error{
            constructor(msg) {
                    super(msg);
                    this.message = msg;
                    this.name = 'MyError';
            }
    };
    
    var myerr = new MyError("test");
    console.log(myerr.stack);
    console.log(myerr);
    

    Output of Chrome console.

    MyError: test
        at MyError (:3:28)
        at :12:19
        at Object.InjectedScript._evaluateOn (:875:140)
        at Object.InjectedScript._evaluateAndWrap (:808:34)
        at Object.InjectedScript.evaluate (:664:21)
    

    Output of Node.js

    MyError: test
        at MyError (/home/bsadmin/test/test.js:5:8)
        at Object. (/home/bsadmin/test/test.js:11:13)
        at Module._compile (module.js:435:26)
        at Object.Module._extensions..js (module.js:442:10)
        at Module.load (module.js:356:32)
        at Function.Module._load (module.js:311:12)
        at Function.Module.runMain (module.js:467:10)
        at startup (node.js:134:18)
        at node.js:961:3
    

提交回复
热议问题