Vincent Pakson
Vincent Pakson

Reputation: 1949

Error: Cannot enqueue Query after fatal error. Expressjs. Mysql

I have my Express js connect to multiple dbs. Which works everytime I startup my app. But As soon as my connection to my database goes stale... the connection returns an error code of PROTOCOL_CONNECTION_LOST. Which is normal for a mysql when a connection is idle. My mysql server is deployed in AWS RDS which also works just fine.

The problem is, everytime my express app encounters the PROTOCOL_CONNECTION_LOST error, it should reconnect to the database, which in fact also works. BUUT when I try to make queries to my MYSQL db. It returns a Error: Cannot enqueue Query after fatal error. error. I've been dealing with this for a while, and my workaround is to restart the express app everytime. hope someone else has encountered this and could give an advice.

Here is my sample code for connecting to db:

var mysql = require('mysql');
var mysqlConn
// mysqlConn.connect();

function handleDisconnect() {
    mysqlConn = mysql.createConnection({
        host: 'aws_instance***',
        user: '******',
        password: '*****',
        database: 'my_db',
        multipleStatements: true
    });

    mysqlConn.connect(function (err) {
        if (err) {
            console.log('ERROR CONNECT admin:', err.code + '--' + err.address);
            setTimeout(handleDisconnect, 2000);
        } else {
            console.log('Connected to DB')
        }
    });

    mysqlConn.on('error', function (err) {
        console.log('ERROR admin', err.code + '--' + err.address);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {   // Connection to the MySQL server is usually
            console.log("Connection to db lost!")
            handleDisconnect();                         // lost due to either server restart, or a
        } else {    
            console.log(err)                                  // connnection idle timeout (the wait_timeout
            throw err;                                  // server variable configures this)
        }
    });

}

handleDisconnect();
module.exports = {
    mysqlConn: mysqlConn,
};

Then here is my output logs as shown in my server logs.

ERROR db PROTOCOL_CONNECTION_LOST--undefined
Connection to db lost!
Connected to db
OPTIONS /verify-token/ 200 0.285 ms - 4
Error: Cannot enqueue Query after fatal error.
POST /verify-token/ 500 1.332 ms - 95
OPTIONS /auth/login 200 0.793 ms - 4
Error: Cannot enqueue Query after fatal error.
POST /login 500 1.564 ms - 58
OPTIONS /login 200 0.687 ms - 4
Error: Cannot enqueue Query after fatal error.
POST /login 500 1.467 ms - 58

Upvotes: 5

Views: 6827

Answers (1)

kungphu
kungphu

Reputation: 4849

While there are workarounds, they apparently don't work for everyone. The suggestion in the documentation is to use connection pooling instead of manually managing individual connections.

Upvotes: 6

Related Questions