javascript - 自定义错误类作为 Node 模块发送自定义错误响应

标签 javascript node.js bluebird node-modules custom-error-handling

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

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

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,但我不知道该怎么做。

最佳答案

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

因此,您可以像这样捕获自定义错误对象

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?

关于javascript - 自定义错误类作为 Node 模块发送自定义错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776385/

相关文章:

javascript - javascript文件中的整数本身

javascript - 将 JSON 转换为 HTML : Uncaught TypeError: json. forEach 不是函数

node.js - sequelize-auto 找不到模块 'sequelize'

javascript - 如何拥有可变数量的 Bluebird promise ? ( Node )

javascript - 按顺序运行 Bluebird Promises,没有返回值?

javascript 表单验证 - 仅字母

javascript - js 和 jquery.dataTables.js 出现错误 : Uncaught SyntaxError: Unexpected token < in jquery-ui.

node.js - 上传进度——请求

javascript - 如何 POST 一个包含对象数组的数组?

javascript - 使用 Bluebird.mapSeries 按顺序处理一组 API 调用