作为一个Node模块的自定义错误类,用于发送自定义错误响应

3

我在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.js 模块,但是我不知道如何做。


1
你为什么要将 messagestacktoJSON 添加到 Error.prototype 中?为什么不直接在 CustomError 中设置它们呢? - thefourtheye
@thefourtheye 为什么要定义 message/stack,它们已经从 Error.prototype 继承了。 - James
@James True。我为什么没想到呢?:D - thefourtheye
@James 啊,我明白为什么 OP 这样做了。他把所有东西都变成了“可枚举的”。 - thefourtheye
@thefourtheye 哦,原来是这样。说实话,我只是浏览了一下实际的实现,因为那与所问的问题并不相关。 - James
@thefourtheye 是的,没错。 - Satyam Koyani
2个回答

2

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

引用Bluebird文档

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

我想把这个转换成一个Node模块,但是我不知道该怎么做。
你只需要将你想要导出作为模块的一部分的内容分配给module.exports。在这种情况下,您很可能希望导出CustomError函数,可以像这样完成:
module.exports = CustomError;

阅读关于module.exports的更多信息,请参考这个问题:什么是Node.js的module.exports,以及如何使用它?


1
一个节点模块就是一个导出的类。在你的例子中,如果你导出你的CustomError类,例如:
module.exports = CustomError;

然后你就可以从另一个类中导入该模块。
var CustomError = require("./CustomError");
...
throw new CustomError();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接