From 4d4f295dd5638f1e0a4dac46ef62da4836a4179a Mon Sep 17 00:00:00 2001 From: Friedel Ziegelmayer Date: Mon, 27 Mar 2017 17:18:55 +0200 Subject: [PATCH] fix(dial): proper error handling on dial (#77) --- package.json | 3 ++- src/index.js | 13 +++++++++++-- test/index.spec.js | 7 +++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index fae1668..239fd3d 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "lodash.isfunction": "^3.0.8", "mafmt": "^2.1.6", "multiaddr": "^2.2.2", + "once": "^1.4.0", "stream-to-pull-stream": "^1.7.2" }, "contributors": [ @@ -60,4 +61,4 @@ "Richard Littauer ", "Stephen Whitmore " ] -} \ No newline at end of file +} diff --git a/src/index.js b/src/index.js index f430ac8..1e4a14d 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,7 @@ const mafmt = require('mafmt') const includes = require('lodash.includes') const isFunction = require('lodash.isfunction') const Connection = require('interface-connection').Connection +const once = require('once') const debug = require('debug') const log = debug('libp2p:tcp:dial') @@ -22,16 +23,24 @@ module.exports = class TCP { cb = () => {} } + cb = once(cb) const cOpts = ma.toOptions() log('Connecting to %s %s', cOpts.port, cOpts.host) - const rawSocket = net.connect(cOpts, cb) - + const rawSocket = net.connect(cOpts) rawSocket.once('timeout', () => { log('timeout') rawSocket.emit('error', new Error('Timeout')) }) + rawSocket.once('error', cb) + + rawSocket.once('connect', () => { + rawSocket.removeListener('error', cb) + cb() + }) + + const socket = toPull.duplex(rawSocket) const conn = new Connection(socket) diff --git a/test/index.spec.js b/test/index.spec.js index a279acd..bbff5cc 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -471,6 +471,13 @@ describe('Connection wrap', () => { ) }) + it('dial error', (done) => { + tcp.dial(multiaddr('/ip4/999.0.0.1/tcp/1234'), (err) => { + expect(err).to.exist() + done() + }) + }) + it('matryoshka wrap', (done) => { const conn = tcp.dial(ma) const connWrap1 = new Connection(conn)