0

I'm using Azure MySQL database in my Node application which works fine except that after few minutes of usage, Azure closes the connection and Node throws error:

Error: read ECONNRESET

What I need is to prevent my Node app from crashing and tell it to reconnect after such exception. I have tried:

var con = mysql.createConnection({
  host: "mydatabase.mysql.database.azure.com",
  user: "nodeapp@mydatabase",
  password: "12345",
  database: "mydatabase",
  port: 3306
});

    process.on('uncaughtException', function(err) {
      con.destroy();
      con.connect();
      console.log(err);
    });

This prevents app from crashing, but my app cannot write to database after this so reconnection fails. How should I reconnect after such error? Any advise is highly appreciated.

Mr. Engineer
  • 215
  • 1
  • 9
  • 26

1 Answers1

0

Reproduced your error: Throw the below error after connecting about 3 minutes.

enter image description here

The reason seems to be some settings on your database like this: wait_timeout=180.

My solutions:

1. raise the value of wait_timeout: enter image description here

2. If this happens when establishing a single reused connection, it can be avoided by establishing a connection pool instead. See this post.

Doris Lv
  • 3,083
  • 1
  • 5
  • 14
  • Thanks for taking the effort. Yeah the exception handling code prevents app from crashing but unfortunately does not reconnect properly. But raising the value of timeout parameter should work, thanks. – Mr. Engineer Apr 13 '21 at 10:43
  • Glad to hear it helps, I would delete the useless part in my answer. – Doris Lv Apr 14 '21 at 01:32