Extending Error in Javascript with ES6 syntax & Babel

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

    With the latest changes in babel 6, I find transform-builtin-extend no longer working. I ended up using this mixed approach:

    export default class MyError {
        constructor (message) {
            this.name = this.constructor.name;
            this.message = message;
            this.stack = (new Error(message)).stack;
        }
    }
    
    MyError.prototype = Object.create(Error.prototype);
    MyError.prototype.constructor = MyError;
    

    and

    import MyError from './MyError';
    
    export default class MyChildError extends MyError {
        constructor (message) {
            super(message);
        }
    }
    

    As a result all these tests pass:

    const sut = new MyError('error message');
    expect(sut.message).toBe('error message');
    expect(sut).toBeInstanceOf(Error);
    expect(sut).toBeInstanceOf(MyError);
    expect(sut.name).toBe('MyError');
    expect(typeof sut.stack).toBe('string');
    
    const sut = new MyChildError('error message');
    expect(sut.message).toBe('error message');
    expect(sut).toBeInstanceOf(Error);
    expect(sut).toBeInstanceOf(MyError);
    expect(sut).toBeInstanceOf(MyChildError);
    expect(sut.name).toBe('MyChildError');
    expect(typeof sut.stack).toBe('string');
    

提交回复
热议问题