1
目前,我正在使用express和mongoose处理RESTful-API,现在我遇到了问题。NodeJS:未处理的承诺在方法结束时拒绝
首先,我的方法:
public create() : Promise<UserDocument> {
return new Promise((user) => {
User.exists(this.username).then((exists) => {
if (exists) {
throw Errors.mongoose.user_already_exists;
} else {
UserModel.create(this.toIUser()).then((result) => {
user(result);
}).catch(() => {
throw Errors.mongoose.user_create
});
}
}).catch((error) => {
throw error;
})
});
}
我得到一个未处理的承诺,拒绝当我执行这个方法。出现这种情况,即使我处理错误,当我执行的方法是这样的:
User.fromIUser(user).create().then(() => {
return response.status(200).send({
message: "Created",
user
});
}).catch((error) => {
return response.status(500).send({
message: error
});
});
完整堆栈跟踪:
(node:23992) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): User already exists
(node:23992) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我如何避免这种情况?
感谢您的帮助, felixoi