From 6a7edabc22e36db7386c97ee93f08f957364f37d Mon Sep 17 00:00:00 2001 From: Yanlong Wang Date: Wed, 14 Sep 2016 10:26:03 +0800 Subject: [PATCH] When connection fail, emit the error. (#28) * When connection fail, emit the error. If client connect failed, emit the connection error rather than swallowing it. * Add test for connection error. --- index.js | 1 + test/events.js | 26 ++++++++++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 10d8dd01..f62f667d 100644 --- a/index.js +++ b/index.js @@ -43,6 +43,7 @@ Pool.prototype._create = function (cb) { if (err) { this.log('client connection error:', err) cb(err) + this.emit('error', err) } else { this.log('client connected') this.emit('connect', client) diff --git a/test/events.js b/test/events.js index bcb523f0..5045cc2c 100644 --- a/test/events.js +++ b/test/events.js @@ -22,7 +22,7 @@ describe('events', function () { }) }) - it('emits "connect" only with a successful connection', function (done) { + it('emits "error" with a failed connection', function (done) { var pool = new Pool({ // This client will always fail to connect Client: mockClient({ @@ -34,7 +34,29 @@ describe('events', function () { pool.on('connect', function () { throw new Error('should never get here') }) - pool._create(function (err) { + pool.on('error', function (err) { + if (err) done() + else done(new Error('expected failure')) + }) + pool.connect() + }) + + it('callback err with a failed connection', function (done) { + var pool = new Pool({ + // This client will always fail to connect + Client: mockClient({ + connect: function (cb) { + process.nextTick(function () { cb(new Error('bad news')) }) + } + }) + }) + pool.on('connect', function () { + throw new Error('should never get here') + }) + pool.on('error', function (err) { + if (!err) done(new Error('expected failure')) + }) + pool.connect(function (err) { if (err) done() else done(new Error('expected failure')) })