no_parachute44
no_parachute44

Reputation: 385

Nodejs custom error class throws "TypeError: ValidationError is not a constructor"

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!

Upvotes: 1

Views: 1939

Answers (1)

Bergi
Bergi

Reputation: 665475

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.

Upvotes: 5

Related Questions