Extending Error in Javascript with ES6 syntax & Babel

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

    As @sukima mentions, you cannot extend native JS. The OP's question cannot be answered.

    Similar to Melbourne2991's answer, I did used a factory rather, but followed MDN's recommendation for customer error types.

    function extendError(className){
      function CustomError(message){
        this.name = className;
        this.message = message;
        this.stack = new Error().stack; // Optional
      }
      CustomError.prototype = Object.create(Error.prototype);
      CustomError.prototype.constructor = CustomError;
      return CustomError;
    }
    

提交回复
热议问题