【问题标题】:Handling Mongoose Query Errors in Express.js处理 Express.js 中的 Mongoose 查询错误
【发布时间】:2021-05-04 15:29:05
【问题描述】:

假设我想在 Express 邮寄路线内对数据库进行 Mongoose 查询:

app.post("/login",(req,res)=>{
    const username = req.body.username
    const password = req.body.password
    User.find({username:username},(err,user)=>{
        if (err) handleError(err)
        //if user exists
        if (user.length) {
            //check password
            if (user.password === password) {
                //assign jwt, redirect
            } else {
                //"username/password is incorrect"
            }
        } else {
            //"username/password is incorrect"
        }
    })
})

我关心的是 handleError 函数。我不太确定在 Mongoose 中甚至会发生什么样的错误,因为它只是一个简单的查询,但是应该在 handleError 函数中包含什么?那时我应该向用户发送什么响应?

【问题讨论】:

    标签: javascript mongodb rest express mongoose


    【解决方案1】:

    我认为你应该:

    • 通过async/await 使用承诺。
    • 不要在中间件中捕获任何错误,并在顶级快速错误处理程序中处理错误。有关此here 的更多信息。
    • 在您的顶级快速错误处理程序中,根据环境,返回一个简单的消息,如:return res.status(500).json({ message: "Our server are unreachable for now, try again later." });,如果它在production 中。如果您在 local 环境中,请返回包含错误的 JSON 有效负载,例如:return res.status(500).json({ err: <Error> });

    总而言之,您的代码应如下所示:

    app.post('/login', async (req, res) {
      
      // ES6 Destructuring
      const { username, password } = req.body;
    
      // Use findOne instead of find, it speeds up the query
      const user = await User.findOne({ username });
    
      if (!user || (user.password !== hashFunction(password))) {
        return res.status(403).json({ message: 'Bad credentials' });
      }
    
      // assign JWT and redirect
    });
    

    【讨论】:

      【解决方案2】:

      您可以只发送带有与 Mongoose 响应相关的描述性消息的错误响应。

      app.post("/login",(req,res)=>{
          const username = req.body.username
          const password = req.body.password
          User.find({username:username},(error,user)=>{
              if (error){
                return res.status(400).json({message:"Can not perform find operation.", error: error });
              }
              //if user exists
              if (user.length) {
                  //check password
                  if (user.password === password) {
                      //assign jwt, redirect
                  } else {
                      //"username/password is incorrect"
                  }
              } else {
                  //"username/password is incorrect"
              }
          })
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 1970-01-01
        • 2012-08-05
        • 2021-09-09
        • 2014-01-16
        • 1970-01-01
        • 2014-01-07
        相关资源
        最近更新 更多