Last active
December 14, 2016 12:18
-
-
Save cristobal/83c7443d4cefab68e4c71e7441a94122 to your computer and use it in GitHub Desktop.
AbstractError + CustomError
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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}]`; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomError extends AbstractError { | |
constructor(message, code) { | |
super(message, {code}); | |
} | |
toString() { | |
return `{ [${this.name}: ${this.message}],\n code: '${this.code}' }`; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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