我对 NodeJS 还很陌生,我仍在试图弄清楚如何处理错误。我读了很多问题,但我不知道我做错了什么。
这里我有一个登录功能:
export const login = async (req, res) => {
let body = req.body;
try {
const user = await User.findOne({ username: body.username });
if (!user) {
throw new InternalError("Username or password are wrong");
}
if (!bcrypt.compareSync(body.password, user.password)) {
throw new InternalError("Username or password are wrong");
}
let token = jwt.sign({ data: user }, "secret", {
expiresIn: 60 * 60 * 24 * 30
});
return res.json({
user: user,
token: token
});
} catch (error) {
throw new GenericError(error);
}
};
这是我得到的错误,例如,我包含错误的密码:
(node:12332) UnhandledPromiseRejectionWarning: GenericError: Username or password are wrong
(node:12332) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by
throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
我知道用 Await 做出的承诺必须有一个.then()and.catch()但这不是执行承诺时的错误,而是验证密码时的错误。我想要的是抛出错误并获得响应。现在请求永远不会结束,并且会显示上一个错误。
BIG阳
相关分类