Skip to content

Commit accaf39

Browse files
committed
adjust prototype chain of base classes, check new.target of HttpError
1 parent 206aa2c commit accaf39

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

index.js

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,9 @@ function createError () {
111111

112112
function createHttpErrorConstructor () {
113113
function HttpError () {
114-
throw new TypeError('cannot construct abstract class')
114+
if (new.target === HttpError) {
115+
throw new TypeError('cannot construct abstract class')
116+
}
115117
}
116118

117119
inherits(HttpError, Error)
@@ -130,13 +132,15 @@ function createClientErrorConstructor (HttpError, name, code) {
130132
function ClientError (message) {
131133
// create the error object
132134
var msg = message != null ? message : statuses.message[code]
133-
var err = new Error(msg)
135+
var err = Reflect.construct(Error, [msg], new.target || ClientError)
134136

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

138-
// adjust the [[Prototype]]
139-
setPrototypeOf(err, ClientError.prototype)
140+
// adjust the [[Prototype]] if new.target is not ClientError
141+
if (new.target && new.target !== ClientError) {
142+
setPrototypeOf(err, new.target.prototype)
143+
}
140144

141145
// redefine the error message
142146
Object.defineProperty(err, 'message', {
@@ -199,13 +203,15 @@ function createServerErrorConstructor (HttpError, name, code) {
199203
function ServerError (message) {
200204
// create the error object
201205
var msg = message != null ? message : statuses.message[code]
202-
var err = new Error(msg)
206+
var err = Reflect.construct(Error, [msg], new.target || ServerError)
203207

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

207-
// adjust the [[Prototype]]
208-
setPrototypeOf(err, ServerError.prototype)
211+
// adjust the [[Prototype]] if new.target is not ClientError
212+
if (new.target && new.target !== ServerError) {
213+
setPrototypeOf(err, new.target.prototype)
214+
}
209215

210216
// redefine the error message
211217
Object.defineProperty(err, 'message', {

0 commit comments

Comments
 (0)