1 回答
TA贡献1859条经验 获得超6个赞
您收到来自节点的警告,因为您在捕获 InternalError 后重新抛出了 GenericError。与其重新抛出 GenericError,不如在调用时返回响应或捕获 GenericError login。
这是您为两者修改的代码。
export const login = async (req, res) => {
// We get the body info
let body = req.body;
try {
// We find the user with the username from the body
const user = await User.findOne({ username: body.username });
// Let's assume no user exists, so we throw an InternalError,
// This skips straight to the catch block.
if (!user) {
throw new InternalError("Username or password are wrong");
}
// We never reach these two statements
// because of the error above being thrown.
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
});
res.json({
user: user,
token: token
});
} catch (err) {
// We caught our InternalError from not having a user above.
// Now we should return a response that the user is invalid.
// I am just going to return the error that we previously threw.
res.json({
error: err
});
}
};
您绝对可以从 catch 块中抛出 GenericError。但是,这样做需要您在调用登录函数的任何地方捕获 GenericError。
export const login = async (req, res) => {
// We get the body info
let body = req.body;
try {
// We find the user with the username from the body
const user = await User.findOne({ username: body.username });
// Let's assume no user exists, so we throw an InternalError,
// This skips straight to the catch block.
if (!user) {
throw new InternalError("Username or password are wrong");
}
// We never reach these two statements
// because of the error above being thrown.
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
});
res.json({
user: user,
token: token
});
} catch (err) {
// Throw the generic error
throw GenericError(err);
}
};
try {
// We call the login function that is defined above.
// It is going to throw a GenericError, so we have to
// catch it.
await login(req, res);
} catch (err) {
// Now we need to catch the generic error
res.json({
error: err
});
}
添加回答
举报