bjyoungblood / es6-error

Easily-extendable error for use with ES6 classes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Consider deprecating this package

cpcallen opened this issue · comments

I don't like to rain on other people's parades, but the examples in the README.md can be rewritten rather more simply as:

ES6 Usage

class MyError extends Error {}
MyError.prototype.name = 'MyError';
Object.defineProperty(MyError.prototype, 'name', {enumerable : false});  // Optional.

ES5 Usage

function MyError(message) {
  return Object.setPrototypeOf(new Error(message), MyError.prototype);
}
Object.setPrototypeOf(MyError.prototype, Error.prototype);
MyError.prototype.name = 'MyError';
Object.defineProperty(MyError.prototype, 'name', {enumerable: false});  // Optional.

These are both (AFAICT) exactly equivalent, and have the following advantages:

  • One fewer external dependency.
  • Shorter and simpler code.
  • The .name goes on the .prototype, instead of every instance. This saves memory and is more consistent with existing Error classes.
  • No .message property is created if no message is supplied to the constructor. This is more consistent with existing Error classes—and of course if you do want a default message, then it's easily done via the constructor as in the existing example.
  • Does not depend on the node.js-specific Error.captureStackTrace function.

Thanks for the feedback.

I've thought for a long time that it would be cleaner to have a Babel plugin that could provide the same functionality at build time instead of runtime (though that unfortunately doesn't help TypeScript users). That would also fix problems like uglification causing unexpected issues like new MyError().name !== 'MyError' as in #31.

I started playing around with such a concept here, but I don't have any experience writing Babel plugins and unfortunately don't have the time these days to dive into making it work correctly (for example, it would need to check if any ancestor classes extend Error).

As far as deprecating the package, I'd be happy to do so, but I would prefer to have an alternative solution to recommend to existing users first.

@bjyoungblood @cpcallen

I started playing around with such a concept here, but I don't have any experience writing Babel plugins and unfortunately don't have the time these days to dive into making it work correctly (for example, it would need to check if any ancestor classes extend Error).

I’ve created Babel plugin just for that: https://github.com/niksy/babel-plugin-native-error-extend