简体   繁体   中英

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM