简体   繁体   中英

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. 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. The site should show error message "wrong password" something like that on the website.

Code is written in node.js and express.js

This is my code: 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

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. dbUserList returns a promise so I made a promise chain with.then().catch() in app.post.

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

Indeed, you have a promise rejection that is not handled:

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

.catch is here at the end of a promise chain, and thus returns a 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.

Instead of throwing, you should just do the sending right at that spot:

res.send({errorMessage: errMessage})

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