Extending Error in Javascript with ES6 syntax & Babel

后端 未结 14 1851
你的背包
你的背包 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:53

    Given this the accepted answer no longer works you could always use a factory as an alternative (repl):

    function ErrorFactory(name) {
       return class AppError extends Error {
        constructor(message) {
          super(message);
          this.name = name;
          this.message = message; 
          if (typeof Error.captureStackTrace === 'function') {
            Error.captureStackTrace(this, this.constructor);
          } else { 
            this.stack = (new Error(message)).stack; 
          }
        }
      }     
    }
    
    // now I can extend
    const MyError = ErrorFactory("MyError");
    
    
    var myerror = new MyError("ll");
    console.log(myerror.message);
    console.log(myerror instanceof Error);
    console.log(myerror.name);
    console.log(myerror.stack);

提交回复
热议问题