3

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

我想赶上这CustomError门课Bluebird Catch promises

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);

我想将其转换为节点模块,但我不知道如何做到这一点。

4

2 回答 2

2

我想在 Bluebird Catch 承诺中捕获这个 CustomError 类。

引用bluebird 的文档

要将参数视为您要过滤的错误类型,您需要构造函数具有其.prototype属性 be instanceof Error

这样的构造函数可以像这样最低限度地创建:

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

使用它:

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
});

我想将其转换为节点模块,但我不知道如何做到这一点。

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

module.exports = CustomError;

module.exports在这个问题中阅读更多信息,Node.js module.exports 的目的是什么以及如何使用它?

于 2015-04-21T15:30:56.607 回答
1

节点模块只不过是一个导出的类。在您的示例中,如果您导出您的CustomError课程,即

module.exports = CustomError;

然后你就可以从另一个类中导入模块

var CustomError = require("./CustomError");
...
throw new CustomError();
于 2015-04-21T15:21:13.367 回答