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

时间:2015-04-21 15:17:51

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

这里我在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);

我想将其转换为 node-module ,但我不知道如何做到这一点。

2 个答案:

答案 0 :(得分:2)

  

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

引用bluebird's documentation

  

要将参数视为要过滤的错误类型,您需要构造函数使其.prototype属性为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;

在此问题What is the purpose of Node.js module.exports and how do you use it?

中详细了解module.exports

答案 1 :(得分:1)

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

module.exports = CustomError;

然后你就可以从另一个类

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