Extending Error in Javascript with ES6 syntax & Babel

后端 未结 14 1910
你的背包
你的背包 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 02:03

    Edit: Breaking changes in Typescript 2.1

    Extending built-ins like Error, Array, and Map may no longer work.

    As a recommendation, you can manually adjust the prototype immediately after any super(...) calls.

    Editing Lee Benson original answer a little bit works for me. This also adds stack and additional methods of ExtendableError class to the instance.

    class ExtendableError extends Error {
       constructor(message) {
           super(message);
           Object.setPrototypeOf(this, ExtendableError.prototype);
           this.name = this.constructor.name;
       }
       
       dump() {
           return { message: this.message, stack: this.stack }
       }
     }    
    
    class MyError extends ExtendableError {
        constructor(message) {
            super(message);
            Object.setPrototypeOf(this, MyError.prototype);
        }
    }
    
    var myerror = new MyError("ll");
    console.log(myerror.message);
    console.log(myerror.dump());
    console.log(myerror instanceof Error);
    console.log(myerror.name);
    console.log(myerror.stack);
    

提交回复
热议问题