Last active
August 29, 2015 14:14
-
-
Save gr0uch/09ca19032ab192524dc6 to your computer and use it in GitHub Desktop.
Custom typed errors in ES6
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
// Hello. There is now a module for this. | |
// https://github.com/0x8890/error-class | |
// $ npm install error-class | |
const hasCaptureStackTrace = 'captureStackTrace' in Error | |
// Internal function to set up an error. | |
function setup (message) { | |
const { constructor, constructor: { name } } = this | |
if (hasCaptureStackTrace) | |
Error.captureStackTrace(this, constructor) | |
else | |
Object.defineProperty(this, 'stack', { | |
value: Error(message).stack | |
}) | |
Object.defineProperties(this, { | |
name: { value: name }, | |
message: { value: message } | |
}) | |
} | |
export class BadRequestError extends Error { | |
constructor () { super(); setup.apply(this, arguments) } | |
} | |
export class UnauthorizedError extends Error { | |
constructor () { super(); setup.apply(this, arguments) } | |
} | |
export class ForbiddenError extends Error { | |
constructor () { super(); setup.apply(this, arguments) } | |
} | |
export class NotFoundError extends Error { | |
constructor () { super(); setup.apply(this, arguments) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment