自定义错误 Class 作为节点模块发送自定义错误响应

Custom Error Class as a Node module to send custom error response

这里我在 Node.js 中创建了自定义错误 class。我创建了这个 ErrorClass 来发送 api 调用的自定义错误响应。

我想在 Bluebird Catch promises.

中捕捉这个 CustomError class
Object.defineProperty(Error.prototype, 'message', {
    configurable: true,
    enumerable: true
});

Object.defineProperty(Error.prototype, 'stack', {
    configurable: true,
    enumerable: true
});

Object.defineProperty(Error.prototype, 'toJSON', {
    value: function () {
        var alt = {};
        Object.getOwnPropertyNames(this).forEach(function (key) {
            alt[key] = this[key];
        }, this);

        return alt;
    },
    configurable: true
});

Object.defineProperty(Error.prototype, 'errCode', {
    configurable: true,
    enumerable: true
});

function CustomError(errcode, err, message) {
    Error.captureStackTrace(this, this.constructor);
    this.name = 'CustomError';
    this.message = message;
    this.errcode = errcode;
    this.err = err;
}

CustomError.prototype = Object.create(Error.prototype);

我想将其转换为 node-module,但我不知道该怎么做。

节点模块只不过是导出的 class。在您的示例中,如果您导出 CustomError class 即

module.exports = CustomError;

然后您就可以从另一个 class

导入模块
var CustomError = require("./CustomError");
...
throw new CustomError();

I want to catch this CustomError class in Bluebird Catch promises.

引用 bluebird's documentation,

For a parameter to be considered a type of error that you want to filter, you need the constructor to have its .prototype property be instanceof Error.

Such a constructor can be minimally created like so:

function MyCustomError() {}
MyCustomError.prototype = Object.create(Error.prototype);

Using it:

Promise.resolve().then(function() {
    throw new MyCustomError();
}).catch(MyCustomError, function(e) {
    //will end up here now
});

所以,你可以catch自定义错误对象,像这样

Promise.resolve().then(function() {
    throw new CustomError();
}).catch(CustomError, function(e) {
    //will end up here now
});

I wanna convert this into node-module but I am not getting how to do that.

您只需将要作为模块的一部分导出的任何内容分配给 module.exports。在这种情况下,您很可能想要导出 CustomError 函数,它可以像这样完成

module.exports = CustomError;

在这个问题中阅读更多关于 module.exports 的信息,What is the purpose of Node.js module.exports and how do you use it?