在这里,我在 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.
For a parameter to be considered a type of error that you want to filter, you need the constructor to have its
.prototype
property beinstanceof 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/