简体   繁体   English

我在 promise 链中有 catch() 但仍然得到未处理的 promise 拒绝

[英]I have catch() in promise chain but still gets unhandled promise rejection

I found a lot of thread which have same problem, but almost all of them didn't have catch() or used promise chain wrong.我发现很多线程都有同样的问题,但几乎所有线程都没有 catch() 或使用 promise 链错误。 I am testing that situation when user gave a wrong password or identification and failed login.当用户输入错误的密码或标识并且登录失败时,我正在测试这种情况。 In my code, I think I used promise chain correctly with catch(), but I still get unhandled promise rejection error.在我的代码中,我想我用 catch() 正确使用了 promise 链,但我仍然得到未处理的 promise 拒绝错误。 The site should show error message "wrong password" something like that on the website.该网站应在网站上显示类似“密码错误”的错误消息。

Code is written in node.js and express.js代码用 node.js 和 express.js 编写

This is my code: app.js这是我的代码:app.js

app.post('/:login',(req,res)=>{
 const userId = req.body.userId;
 const userPw = req.body.userPW;
 try{
  if(userId.length<5&&userPw.length<5){
    throw "Id and password must be minimum 5 characters";
  }else if(userId.length>=5&&userPw.length<5){
    throw "Password must be minimum 5 characters";
  }else if(userId.length<5&&userPw.length>=5){
    throw "Id must be minimum 5 characters";
  }else{
    dbFile.checkIfUserExists(userId,userPw,res)
    .then((response)=>{
      console.log(response[0].userId);
      return response[0].userId;
    }).catch((errMessage)=>{
      console.log(errMessage);
      throw errMessage;
    })
  }
}
 catch(e){
  console.log(e);
  res.send({
    errorMessage:e
  })
 }
});

userListDB.js userListDB.js

const mysql = require('mysql');

function createMySQLConnection(){
    const connection = mysql.createConnection({
        host:'localhost',
        user:'root',
        password:'',
        database:'chatdatabase'
    });
    return connection;
}
function connectToDB(connection){
    try{
        connection.connect(function(err){
            if(err){
                throw "Sorry, something happened. Please try later";
            }
        })
    }catch(error){
        return error;
    }
}
module.exports={
    checkIfUserExists:function(id,pw,res){
        const connection = createMySQLConnection();
        if(connectToDB(connection)===undefined||connectToDB(connection)===null){
            const sql = "SELECT * FROM userlist WHERE userId=? AND password=?";
            return new Promise((resolve,reject)=>{
                connection.query(sql,[id,pw],(error,result)=>{
                    try{
                        if(error){
                            throw error;
                        }
                        else if(result.length===0){
                            throw "It seems like your id and password don't match. please try again with different id and password";
                        }
                        else{
                            resolve(result);
                        }
                    }catch(e){
                        reject(e);
                    }
                })
            })
        }
    }
}

I know I didn't do password encryption but I will do it later when this problem is fixed.我知道我没有进行密码加密,但我稍后会在此问题解决后进行。 As you see in the code, when user sends a POST login request, app.post in app.js will validate data and if there is no problem it will call dbFile.checkIfUserExists from dbUserList.js.正如您在代码中看到的,当用户发送 POST 登录请求时,app.js 中的 app.post 将验证数据,如果没有问题,它将从 dbUserList.js 调用 dbFile.checkIfUserExists。 dbUserList returns a promise so I made a promise chain with.then().catch() in app.post. dbUserList 返回一个 promise 所以我在 app.post 中用.then().catch() 制作了一个 promise 链。

But I still get但我仍然得到

It seems like your id and password don't match. please try again with different id and password
(node:7896) UnhandledPromiseRejectionWarning: It seems like your id and password don't match. please try again with different id and password
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7896) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7896) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I found console.log in then().catch() works so there should not be any problem in both try catches and I cannot understand why my code still shows unhandled promise rejection我发现 then().catch() 中的 console.log 有效,所以两个 try catch 都不应该有任何问题,我不明白为什么我的代码仍然显示未处理的 promise 拒绝

Indeed, you have a promise rejection that is not handled:实际上,您有一个未处理的 promise 拒绝:

.catch((errMessage)=>{
  console.log(errMessage);
  throw errMessage;
})

.catch is here at the end of a promise chain, and thus returns a promise. .catch位于 promise 链的末尾,因此返回 promise。 Now if you get into the catch callback and throw , then that will put that promise in a rejected state, and there is no more handler for that rejection.现在,如果您进入catch回调并throw ,那么这会将 promise 放入被拒绝的 state 中,并且没有更多的处理程序来处理该拒绝。

Instead of throwing, you should just do the sending right at that spot:而不是扔,你应该在那个地方直接发送:

res.send({errorMessage: errMessage})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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