这里我在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 ,但我不知道如何做到这一点。
答案 0 :(得分:2)
我想在Bluebird Catch承诺中捕获这个CustomError类。
要将参数视为要过滤的错误类型,您需要构造函数使其
.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();