How to properly handle NodeJs Error: Read ECONNRESET

256 views Asked by At

I know there might be a popular question on SO on this error but it doesn't help and every google search leads back to the same question.

I have a NodeJs project and what I simply want to do is run setinterval to generate a value every second, insert into Mysql DB and emit to every connected client through websocket.

I have written all the code and this works perfectly only that from time to time i.e sometimes 24 hours, sometimes it could stay for up to 2 days it then crashes with the error code

Error: read ECONNRESET
0|app      | 2023-10-16T09:05:47:     at TCP.onStreamRead (node:internal/stream_base_commons:217:20)

I also get another error

Error: Connection lost: The server closed the connection.
Code: PROTOCOL_CONNECTION_LOST

But I have been able to fix it by adding this to my code which reconnect to my DB if the connection closes

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

But this only fixes the PROTOCOL_CONNECTION_LOST and not ECONNRESET. Anything I am doing wrong or can do better?

0

There are 0 answers