在这里,我在Node.js中创建了Custom Error类。我创建了此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);

我想将其转换为 Node 模块,但我没有得到如何做。

最佳答案


引用bluebird's documentation

因此,您可以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的信息What is the purpose of Node.js module.exports and how do you use it?

10-08 15:45