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
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');