Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

mysql - 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.

question from:https://stackoverflow.com/questions/65870248/nodejs-mysql2-not-throwing-connection-or-query-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...