Extending Error in Javascript with ES6 syntax & Babel

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

    Not using Babel, but in plain ES6, the following seems to work fine for me:

    class CustomError extends Error {
        constructor(...args) {
            super(...args);
            this.name = this.constructor.name;
        }
    }
    

    Testing from REPL:

    > const ce = new CustomError('foobar');
    > ce.name
    'CustomError'
    > ce.message
    'foobar'
    > ce instanceof CustomError
    true
    > ce.stack
    'CustomError: foobar\n    at CustomError (repl:3:1)\n ...'
    

    As you can see, the stack contains both the error name and message. I'm not sure if I'm missing something, but all the other answers seem to over-complicate things.

提交回复
热议问题