Nodejs 自定义错误类抛出“TypeError: ValidationError is not a constructor”

no_*_*e44 1 javascript node.js ecmascript-6

看看有关构建类的其他一些问题,我无法弄清楚我在这里做错了什么。

我有一个名为 ValidationError 的自定义错误类,位于文件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;
Run Code Online (Sandbox Code Playgroud)

我在另一个文件中需要这个类,如下所示:

const { ValidationError } = require('./validationError');
Run Code Online (Sandbox Code Playgroud)

并像这样调用它,这是抛出错误的行:

const validationError = new ValidationError('JSON failed validation.', result.errors);
Run Code Online (Sandbox Code Playgroud)

抛出的错误是“TypeError:ValidationError 不是构造函数”。

我在节点 10.6.4。

那么我在这里做错了什么?谢谢您的帮助!

Ber*_*rgi 5

您不是使用.ValidationError构造函数导出对象,而是直接将类设置为module.exports. 所以在你的导入中应该是

const ValidationError = require('./validationError');
Run Code Online (Sandbox Code Playgroud)

并且不使用解构语法。