Extending Error in Javascript with ES6 syntax & Babel

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

    Combining this answer, this answer and this code, I have made this small "helper" class, that seems to work fine.

    class ExtendableError extends Error {
      constructor(message) {
        super();
        this.message = message; 
        this.stack = (new Error()).stack;
        this.name = this.constructor.name;
      }
    }    
    
    // now I can extend
    
    class MyError extends ExtendableError {
      constructor(m) {   
        super(m);
      }
    }
    
    var myerror = new MyError("ll");
    console.log(myerror.message);
    console.log(myerror instanceof Error);
    console.log(myerror.name);
    console.log(myerror.stack);
    

    Try in REPL

提交回复
热议问题