Search code examples
mysqlnode.jsexpressnode-mysql

NodeJS (Express) with MySQL - How to handle connection resets?


I'm running my website with NodeJS, I'm using the Express framework. Since MySQL is the only database type at my hosting, I went with it.

I created a db.js file:

const mysql = require('mysql');

const con = mysql.createConnection({
    host: .........
    user: ...........
    password: ............
    database: ............
});
  
con.connect(function(err) {
    if (err) {
        //throw err;
        console.error(err.message);
    } else {
        console.log('Connected Ro MySQL!');
    }
});

module.exports = con;

And I using it like:

const db = require(path.join(__dirname, 'db'));

    db.query('select * from table where name = ?', request.params.id, (error, result) => {
        if (error) { 
            response.send(error.message);
        } else {
            //My Render Stuffs Here
            });
        }
    });

My website works fine however sometimes let's say once every 2 weeks there is a MySQL connection reset, I think the database not available for a minute or so for some reason, and then my website crashes, I have to manually restart NodeJS what is very annoying.

Error in the console:

node:events:355
      throw er; // Unhandled 'error' event
      ^
Error: read ECONNRESET
    at TCP.onStreamRead (node:internal/stream_base_commons:211:20)
[...]
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read',
  fatal: true
}

How should I change my codes to prevent crashing? I replaced throw err; with the console.error(err.message); but it only works when I start the website, not when a connection reset happens at runtime.


Solution

  • Found the solution: Replace createConnection with createPool and totally remove con.connect since createPool doesn't need it. That's it, now it's not crashes when the db unavailable.