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 HttpError extension by ES6 classes #98

Open
nathanlepori opened this issue Jun 21, 2023 · 2 comments · May be fixed by #111 or #105
Open

Allow HttpError extension by ES6 classes #98

nathanlepori opened this issue Jun 21, 2023 · 2 comments · May be fixed by #111 or #105

Comments

@nathanlepori
Copy link

To allow better interoperability with ES6 classes (which are forced to call the super() constructor) it is better to add the following condition to the HttpError constructor:

if (this.constructor === HttpError) {
    throw new TypeError('cannot construct abstract class')
}

This way the class can be extended with a concrete class like this:

class MyHttpError extends HttpError {
    constructor() {
        super();
        ...
    }
}

A variant using ES6 classes as base class is shown here but the same works with old school constructor functions as well.

@jonchurch
Copy link
Member

moving this comment and repro from another issue #101 :

#101 (comment)

I was surprised I couldn't subclass errors. I would have expected my ValidationError class would support an instanceof check against itself.

const { BadRequest } = require('http-errors')
const assert = require('assert')


class ValidationError extends BadRequest {}

const err = new ValidationError()
console.log(err.name)
// "BadRequestError"

// err should be an instance of ValidationError
assert(err instanceof ValidationError)

https://runkit.com/cdignam-segment/6536e492c20c690008824a73

@jonchurch
Copy link
Member

There's two different concepts in this issue.

Extending HttpError is not possible currently because of the throw to prevent instantiating the abstract class.

const createErrors = require('http-errors')

class NewBase extends createErrors.HttpError // this will throw a type error

Extending error classes like NotFound do not wire up the prototype properly to be able to check insanceof on it.

const createErrors = require('http-errors')

class ValidationError extends createErrors.BadRequest {}

assert(err instanceof ValidationError) // false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants