Skip to content

Instantly share code, notes, and snippets.

@cristobal
Last active December 14, 2016 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristobal/83c7443d4cefab68e4c71e7441a94122 to your computer and use it in GitHub Desktop.
Save cristobal/83c7443d4cefab68e4c71e7441a94122 to your computer and use it in GitHub Desktop.
AbstractError + CustomError
// @see https://github.com/bjyoungblood/es6-error
// @see http://dailyjs.com/2014/01/30/exception-error/
import {map} from 'lodash';
const defineProperty = (obj, prop, value) => {
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: false,
value
});
};
class AbstractError {
constructor(message, props = {}) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
defineProperty(this, 'message', message);
defineProperty(this, 'name', this.constructor.name);
let propertyDefiner = (value, prop) => {
defineProperty(this, prop, value)
};
map(
props,
propertyDefiner.bind(this)
);
}
// NOTE: override toString in subclass for more complex formatting
toString() {
return `[${this.name}: ${this.message}]`;
}
}
class CustomError extends AbstractError {
constructor(message, code) {
super(message, {code});
}
toString() {
return `{ [${this.name}: ${this.message}],\n code: '${this.code}' }`;
}
}
expect(err).to.be.an.instanceof(CustomError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment