简体   繁体   中英

Nodejs mysql2 not throwing connection or query error

I am trying to capture connection error on nodejs while using mysql or mysql2 node module. My code is

    console.log("Connecting to database")
    try{
        var connection = mysql.createConnection({
            host     : process.env.DB_HOST,
            user     : process.env.DB_USERNAME,
            password : process.env.DB_PASSWORD,
            database : process.env.DB_NAME
        });
        connection.connect();
        console.log("Connected")
    }
    catch(exce)
    {
        console.log(exce)
    }

The mysql server is not running and all details are wrong here. I am expecting this code to throw a connection error but this does not happen. Instead, I am receiving the following console output.

Connecting to database
Connected

I don`t know why there is no connection error thrown by mysql module.

The following solution suggested by @Anatoly worked for me.

var mysql=require("mysql2/promise")
 var connected=true
    console.log("Connecting to database")
    try{
        var connection =await mysql.createConnection({
            host     : process.env.DB_HOST,
            user     : process.env.DB_USERNAME,
            password : process.env.DB_PASSWORD,
            database : process.env.DB_NAME
        });
        // connection.connect();
        console.log("Connected")
    }
    catch(exce)
    {
        console.log(exce)
        connected=false
    }
```

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