【发布时间】:2020-11-28 16:59:03
【问题描述】:
我正在开发一个 NodeJS 应用程序,我正在使用 mongoose 将数据保存到我的 MongoDB 数据库中。
我的控制器可以在/register url 上接收带有一些数据的POST 请求。看起来像这样:
router.post("/register", async (req: Request, res: Response) => {
const accountModel: IRegistrationAccount = {
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password,
repeatedPassword: req.body.repeatedPassword,
};
try {
registerAccount(accountModel);
res.status(OK).send("Registration successful.");
} catch (err) {
res.status(NOT_ACCEPTABLE).send(err);
}
});
如您所见,我想向用户返回一条错误消息,以便他们确切知道出了什么问题。这是registerAccount 方法:
export function registerAccount(accountModel: IRegistrationAccount) {
if (accountModel.firstName.length === 0)
throw "Your first name may not be empty.";
if (accountModel.email.length < 3) throw "Your email is too short.";
if (accountModel.password !== accountModel.repeatedPassword)
throw "The passwords You entered don't match.";
if (accountModel.password.length < 8) throw "Your password is too short.";
const account = new Account(accountModel);
account.save(function (err) {
if (err) return logger.err(err);
return logger.info("Created account.");
});
}
当用户输入的数据有问题时,我使用 throw 返回一条错误消息,然后在控制器中捕获该消息。问题是:我如何知道save 中的回调函数是否抛出了错误以及如何处理该错误?这是我第一次使用 Node,我尝试搜索但找不到合适的答案。
【问题讨论】:
标签: node.js typescript mongoose error-handling callback