Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow proper prototype inheritance and subclassing #105

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
*/

var deprecate = require('depd')('http-errors')
var setPrototypeOf = require('setprototypeof')
var statuses = require('statuses')
var inherits = require('inherits')
var toIdentifier = require('toidentifier')
Expand Down Expand Up @@ -111,7 +110,9 @@ function createError () {

function createHttpErrorConstructor () {
function HttpError () {
throw new TypeError('cannot construct abstract class')
if (!new.target || new.target === HttpError) {
throw new TypeError('cannot construct abstract class')
}
}

inherits(HttpError, Error)
Expand All @@ -130,14 +131,11 @@ function createClientErrorConstructor (HttpError, name, code) {
function ClientError (message) {
// create the error object
var msg = message != null ? message : statuses.message[code]
var err = new Error(msg)
var err = Reflect.construct(Error, [msg], new.target || ClientError)

// capture a stack trace to the construction point
Error.captureStackTrace(err, ClientError)

// adjust the [[Prototype]]
setPrototypeOf(err, ClientError.prototype)

// redefine the error message
Object.defineProperty(err, 'message', {
enumerable: true,
Expand Down Expand Up @@ -199,14 +197,11 @@ function createServerErrorConstructor (HttpError, name, code) {
function ServerError (message) {
// create the error object
var msg = message != null ? message : statuses.message[code]
var err = new Error(msg)
var err = Reflect.construct(Error, [msg], new.target || ServerError)

// capture a stack trace to the construction point
Error.captureStackTrace(err, ServerError)

// adjust the [[Prototype]]
setPrototypeOf(err, ServerError.prototype)

// redefine the error message
Object.defineProperty(err, 'message', {
enumerable: true,
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
"dependencies": {
"depd": "2.0.0",
"inherits": "2.0.4",
"setprototypeof": "1.2.0",
"statuses": "2.0.1",
"toidentifier": "1.0.1"
},
Expand Down
63 changes: 63 additions & 0 deletions test/inheritance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const createError = require('../index')
var assert = require('assert')

function getProtoChain (object) {
const chain = []
let proto = Object.getPrototypeOf(object)
while (proto) {
chain.push(proto.constructor.name)
proto = Object.getPrototypeOf(proto)
}
return chain
}

function getProtoString (object) {
return getProtoChain(object).join('.')
}

describe('Inheritance', () => {
it('Subclasses are instances of themselves', () => {
class CustomError extends createError.NotFound {}
const err = new CustomError()

assert.ok(err instanceof CustomError, `Subclass not instanceof itself: looking for CustomError ${getProtoString(err)}`)
})
it('Subclasses are instances of their ancestors', () => {
class CustomError extends createError.NotFound {}
class MoreCustom extends CustomError {}
const err = new MoreCustom()

assert.ok(err instanceof Error, `Subclass not instanceof its ancestor: looking for Error ${getProtoString(err)}`)
assert.ok(err instanceof createError.HttpError, `Subclass not instanceof its grandparent: looking for HttpError ${getProtoString(err)}`)
assert.ok(err instanceof createError.NotFound, `Subclass not instanceof its grandparent: looking for NotFound ${getProtoString(err)}`)
assert.ok(err instanceof CustomError, `Subclass not instanceof its parent: looking for CustomError ${getProtoString(err)}`)
})
})

describe('Inheritance without new keyword', () => {
it('createError returns errors that are instances of the associated status\' constructor', () => {
const err = createError(404, 'Custom message', { customProperty: 'custom value' })

assert.ok(err.customProperty === 'custom value', `Custom property not set: looking "for custom value", found ${err.customProperty}`)
assert.ok(err instanceof createError.NotFound, `Instance not instanceof itself: looking for NotFound ${getProtoString(err)}`)

const serverError = createError({ customProperty: 'custom value' })

assert.ok(serverError.customProperty === 'custom value', `Custom property not set: looking "for custom value", found ${err.customProperty}`)
assert.ok(serverError instanceof createError.InternalServerError, `Instance not instanceof itself: looking for InternalServerError ${getProtoString(err)}`)
})

it('Dynamic constructor factory functions return instances of themselves', () => {
const err = createError.NotFound('Not Found')

assert.ok(err instanceof createError.NotFound, `Instance not instanceof itself: looking for NotFound ${getProtoString(err)}`)
})

it('Dynamic constructor factory functions return instances of their ancestors', () => {
const err = createError.NotFound('Not Found')

assert.ok(err instanceof Error, `Subclass not instanceof its ancestor: looking for Error ${getProtoString(err)}`)
assert.ok(err instanceof createError.HttpError, `Subclass not instanceof its grandparent: looking for HttpError ${getProtoString(err)}`)
})
})

29 changes: 28 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,29 @@ describe('createError.isHttpError(val)', function () {
})
})

describe('Subclass Instantiation', function () {
it('should allow instantiation of ClientError subclasses', function () {
assert.doesNotThrow(() => {
// eslint-disable-next-line no-new
new createError.NotFound()
})
assert.doesNotThrow(() => {
// eslint-disable-next-line no-new
createError.NotFound()
})
})

it('should allow instantiation of ServerError subclasses', function () {
assert.doesNotThrow(() => {
// eslint-disable-next-line no-new
new createError.InternalServerError()
})
assert.doesNotThrow(() => {
createError.InternalServerError()
})
})
})

describe('HTTP Errors', function () {
it('createError(status, props)', function () {
var err = createError(404, {
Expand Down Expand Up @@ -336,10 +359,14 @@ describe('HTTP Errors', function () {
assert.strictEqual(err.expose, false)
})

it('new createError.HttpError()', function () {
it('should throw when directly instantiating HttpError', function () {
assert.throws(function () {
new createError.HttpError() // eslint-disable-line no-new
}, /cannot construct abstract class/)

assert.throws(function () {
createError.HttpError()
}, /cannot construct abstract class/)
})

it('new createError.NotFound()', function () {
Expand Down
Loading