Skip to content

Unhandled 'error' event with connections #2096

@Steague

Description

@Steague

Probably related to #2049

Error:

events.js:183
      throw er; // Unhandled 'error' event
      ^

Error: Connection lost: The server closed the connection.
    at Protocol.end (/Users/steagu/src/parc-aprmds-warm-storage-api/node_modules/mysql/lib/protocol/Protocol.js:113:13)
    at Socket.<anonymous> (/Users/steagu/src/parc-aprmds-warm-storage-api/node_modules/mysql/lib/Connection.js:109:28)
    at emitNone (events.js:111:20)
    at Socket.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)

Versions:

$ npm -v connect-mysql
6.1.0
$ node -v
v8.11.2
$ npm -v mysql
6.1.0

The error occurs after leaving the app running for many hours and then attempting a new query. The code below is what I am using:

Code:

import dotenv from 'dotenv';
import mysql from 'mysql';

dotenv.config();

let _instance = null;

export default class Mysql {
    constructor() {
        if (!_instance) {
            _instance = this;
        }

        this._type = 'DB';
        this._conn = mysql.createConnection({
            host     : process.env.MYSQL_HOST,
            user     : process.env.MYSQL_USER,
            password : process.env.MYSQL_PASSWORD,
            database : process.env.MYSQL_DATABASE
        });

        return _instance;
    }

    get type() {
        return this._type;
    }

    set type(value) {
        this._type = value;
    }

    async query(sql, arr = []) {
        return await new Promise((resolve, reject) => {
            this._conn.config.queryFormat = (query, values) => {
                if (!values) return query;
                return query.replace(/:(\w+)/g, (txt, key) => {
                    if (values.hasOwnProperty(key)) {
                        return mysql.escape(values[key]);
                    }
                    return txt;
                });
            };

            this._conn.query(sql, arr, (err, results, fields) => {
                if (err) {
                    reject(err);
                    return;
                }

                resolve({
                    results,
                    fields
                });
            });
        });
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions