简体   繁体   English

在 Node.JS 中处理错误的正确方法是什么?

[英]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-catchasync-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.

相关问题 处理Node.js + Express应用程序中所有错误的最佳正确方法是什么? - What's the best proper way to handle all errors in Node.js + Express app? 在 node.js 变换 stream 中处理背压的正确方法是什么? - What's the proper way to handle back-pressure in a node.js Transform stream? Node.js:如何以正确的方式处理承诺变更 - Node.js: How to handle promise-changing in a proper way 在 Node.js 中发生 ERR_STREAM_PREMATURE_CLOSE 错误后释放套接字的正确方法是什么? - What is the proper way to release a socket after an ERR_STREAM_PREMATURE_CLOSE error occured in Node.js? 终止Node.js服务器请求的正确方法是什么? - What's the proper way of terminating a Node.js server request? Node.js:拆分代码的正确方法是什么? - Node.js: What is the proper way of splitting code? 使用node.js postgresql模块的正确方法是什么? - What is the proper way to use the node.js postgresql module? 启动多个本地 node.js 服务器的正确方法是什么? - What is the proper way to start multiple local node.js servers? 在 node.js express 中返回响应的正确方法是什么? - What is the proper way of returning responses in node.js express? 在Node.js 7中,什么是压缩UnhandledPromiseRejectionWarning的正确方法? - In Node.js 7 what is the proper way to suppress UnhandledPromiseRejectionWarning?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM