Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS Mysql PROTOCOL ENQUEUE AFTER FATAL ERROR

Tags:

node.js

mysql

What does the error mean?

{ [Error: Cannot enqueue Query after fatal error.] code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }

This code works in my test file:

function handleDisconnect() {
    objConn = mysql.createConnection(db_config);    // Recreate the connection, since
                                                    // the old one cannot be reused.
    objConn.connect(function(err) {                 // The server is either down
        if(err) {                                   // or restarting (takes a while sometimes).
            console.log('error when connecting to db:', err.code);
            setTimeout(handleDisconnect, 2000);     // We introduce a delay before attempting to reconnect,
        }else{
            console.log('Connected to db!');
        }                                           // to avoid a hot loop, and to allow our node script to
    });                                             // process asynchronous requests in the meantime.
                                                    // If you're also serving http, display a 503 error.
    objConn.on('error', function(err) {
        if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
            handleDisconnect();                       // lost due to either server restart, or a
        }else{
            throw err;
        }
    });
}

handleDisconnect();
megaLoop();

function megaLoop(){
    objConn.query('SELECT u.`email` FROM `users` as u', function(err, rows) {
        console.log(err);
        console.log(rows);
    });
    setTimeout(megaLoop, 100); 
}

But when I use the function in my Express App I get the error:

{ [Error: Cannot enqueue Query after fatal error.] code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR', fatal: false }

Why does it work in my test and not my app?

like image 484
Krister Johansson Avatar asked Jul 21 '15 20:07

Krister Johansson


1 Answers

I had similar issue connecting with MySQL. I solved this issue using connection pool. The concept is to get a connection from a connection pool only when required and release it after use. That way the connection will not be in unstable state. You can get implementation details here.

like image 101
Sawal Maskey Avatar answered Oct 13 '22 17:10

Sawal Maskey