1

Looking at some of the other questions on constructing classes, I can't figure out what I'm doing wrong here.

I have a custom error class called ValidationError that lives in the file validationError.js:

class ValidationError extends Error {
constructor(message, errors) {
    super(message);
    this.errors = errors;
    this.name = this.constructor.name;
    if (typeof Error.captureStackTrace === 'function') {
        Error.captureStackTrace(this, this.constructor);
    } else {
        this.stack = (new Error(message)).stack;
    }
}
}

module.exports = ValidationError;

I require this class in another file like so:

const { ValidationError } = require('./validationError');

And call it like this, which is the line that throws the error:

const validationError = new ValidationError('JSON failed validation.', result.errors);

The thrown error is, "TypeError: ValidationError is not a constructor".

I am on Node 10.6.4.

So what am I doing wrong here? Thanks for the help!

2
  • Looks fine to me. Are you using native ES6 or is there a transpilation step? Commented Feb 27, 2018 at 15:37
  • I'd recommend Error.captureStackTrace(this, new.target); (though actually this should happen inside the super call already) Commented Feb 27, 2018 at 15:38

1 Answer 1

5

You're not exporting an object with a .ValidationError constructor, you're directly setting the class as the module.exports. So in your import it should be

const ValidationError = require('./validationError');

and not use destructuring syntax.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.