Skip to content

Instantly share code, notes, and snippets.

@gr0uch
Last active August 29, 2015 14:14
Show Gist options
  • Save gr0uch/09ca19032ab192524dc6 to your computer and use it in GitHub Desktop.
Save gr0uch/09ca19032ab192524dc6 to your computer and use it in GitHub Desktop.
Custom typed errors in ES6
// 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