如何在 JS 模块中定义错误 类

How to define error classes in a JS module

我正在 API 工作,我正在尝试以一种干净的方式管理错误。 所以我尝试定义一个模块,收集我可能想放入 API.
的所有 Error sub类 那些 类 对应于我想 return 给请求者的 HTTP 错误代码。我选择将它们单独放在一个模块中,因为我还将在其他几个模块中使用它们。

我想像这样使用我的错误子类:

require('../apiErrors');

function apiRequest(req, res) {
   doRequest(req, function (err, data) {
        if (err) {
            throw new BadRequestError('Request is not good');
        }
        res.send(200, data);
   }) 
}

我的模块是这样定义的:apiErrors.js

module.exports = () => {
    class UnauthorizedError extends Error {
        constructor(message) {
             super(message);
             this.name = 'UnauthorizedError';
             this.code = 403;
        }
    }

    class NotFoundError extends Error {
        constructor(message) {
            super(message);
            this.name = 'NotFoundError';
            this.code = 404;
        }
    }

    class BadRequestError extends Error {
        constructor(message) {
            super(message);
            this.name = 'BadRequestError';
            this.code = 400;
        }
    }
};

结果是 ReferenceError: BadRequestError is not defined。 在这一点上,我想知道我这样做的方式是否确实干净,以及在导出我的 apiErrors 模块时我遗漏了什么。

你有两个问题:

  1. 您没有导出 类。您正在导出一个函数,如果您调用它会创建 类,但随后会丢弃它们,因为它不会对它们执行任何操作。

  2. 您没有对 require('../apiErrors');

  3. 的结果做任何事情

要修复 #1,可以:

class UnauthorizedError extends Error {
    constructor(message) {
         super(message);
         this.name = 'UnauthorizedError';
         this.code = 403;
    }
}

class NotFoundError extends Error {
    constructor(message) {
        super(message);
        this.name = 'NotFoundError';
        this.code = 404;
    }
}

class BadRequestError extends Error {
    constructor(message) {
        super(message);
        this.name = 'BadRequestError';
        this.code = 400;
    }
};
module.exports = {
    UnauthorizedError,
    NotFoundError,
    BadRequestError
};

module.exports.UnauthorizedError = class UnauthorizedError extends Error {
    constructor(message) {
         super(message);
         this.name = 'UnauthorizedError';
         this.code = 403;
    }
};

module.exports.NotFoundError = class NotFoundError extends Error {
    constructor(message) {
        super(message);
        this.name = 'NotFoundError';
        this.code = 404;
    }
};

module.exports.BadRequestError = class BadRequestError extends Error {
    constructor(message) {
        super(message);
        this.name = 'BadRequestError';
        this.code = 400;
    }
}

要修复 #2,在您仅使用 BadRequestError:

的示例中
const { BadRequestError } = require('../apiErrors');

const BadRequestError = require('../apiErrors').BadRequestError;

const ErrorClasses = require('../apiErrors');
// ...then to use one of them...
throw new ErrorClasses.BadRequestError('Request is not good');