[英]What is the proper way to handle an error in Node.JS?
This post request creates a new user account and saves a test score data point for a user.此发布请求创建一个新的用户帐户并为用户保存一个测试分数数据点。
~1/20 users or so run into an error and are redirected back to the previous page thus losing their results.大约 1/20 的用户遇到错误并被重定向回上一页,从而丢失了结果。
I have been unable to replicate the error or see any errors in the logs.我无法复制错误或在日志中看到任何错误。
Looking for advice on how to change my error handling and or any insight to why this may be occurring.寻找有关如何更改我的错误处理的建议,或者对可能发生这种情况的任何见解。
Thank you!谢谢!
router.post("/test", function(req, res){
User.findOne({username: req.body.username}, function(err, existingUser) {
console.log('user exists:' + existingUser)
if (err) {
return done(err);
}
if (!existingUser) {
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
user.testscore = req.body.testscore;
user.save()
if(err){
req.flash("error", err.message);
console.log(err)
res.redirect('back')
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/thank-you");
});
});
You can use try-catch
along with async-await
for error handling.您可以使用
try-catch
和async-await
进行错误处理。 I would write the code like this.我会这样写代码。
router.post('/test', async (req, res) => {
try {
const user = await User.findOne({username: req.body.username})
if (!user) {
let newUser = new User({username: req.body.username});
// If User.register returns promise then here also you can use await like above.
// If any error occurs catch block will catch it and show the error.
User.register(newUser, req.body.password, function(err, user) {
user.testscore = req.body.testscore;
user.save()
if(err) {
req.flash("error", err.message);
console.log(err)
res.redirect('back')
return res.render("register");
}
passport.authenticate("local")(req, res, function() {
res.redirect("/thank-you");
});
});
}
} catch (err) {
console.error(err.message)
}
})
Hope it helps to solve your problem.希望它有助于解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.