diff --git a/fastify.js b/fastify.js index aea0a7efc0..95b86aa516 100644 --- a/fastify.js +++ b/fastify.js @@ -167,13 +167,29 @@ function build (options) { const _cb = (hasAddress) ? cb : address fastify.ready(function (err) { if (err) return _cb(err) + if (listening) { + return _cb(new Error('Fastify is already listening')) + } + + server.on('error', wrap) if (hasAddress) { - server.listen(port, address, _cb) + server.listen(port, address, wrap) } else { - server.listen(port, _cb) + server.listen(port, wrap) } listening = true }) + + function wrap (err) { + server.removeListener('error', wrap) + if (_cb) { + _cb(err) + } else { + // this will crash the process + // it will go to 'uncaughtException' + throw err + } + } } function startHooks (req, res, params, store) { diff --git a/test/listen.test.js b/test/listen.test.js index f9ea54fae3..e1b0eebda8 100644 --- a/test/listen.test.js +++ b/test/listen.test.js @@ -2,23 +2,26 @@ const test = require('tap').test const Fastify = require('..') -const fastify = Fastify() test('listen accepts a port and a callback', t => { t.plan(2) + const fastify = Fastify() fastify.listen(0, (err) => { fastify.server.unref() t.error(err) t.pass() + fastify.close() }) }) test('listen accepts a port, address, and callback', t => { t.plan(2) + const fastify = Fastify() fastify.listen(0, '127.0.0.1', (err) => { fastify.server.unref() t.error(err) t.pass() + fastify.close() }) }) @@ -31,6 +34,7 @@ test('listen after Promise.resolve()', t => { f.server.unref() t.error(err) t.pass() + f.close() }) }) }) @@ -56,3 +60,28 @@ test('register after listen using Promise.resolve()', t => { }) }) }) + +test('double listen errors', t => { + t.plan(2) + const fastify = Fastify() + fastify.listen(0, (err) => { + t.error(err) + fastify.listen(fastify.server.address().port, (err) => { + t.ok(err) + fastify.close() + }) + }) +}) + +test('listen twice on the same port', t => { + t.plan(2) + const fastify = Fastify() + fastify.listen(0, (err) => { + t.error(err) + const s2 = Fastify() + s2.listen(fastify.server.address().port, (err) => { + fastify.close() + t.ok(err) + }) + }) +}) diff --git a/test/route.test.js b/test/route.test.js index 14c812aad8..aa0b9a4d1e 100644 --- a/test/route.test.js +++ b/test/route.test.js @@ -76,14 +76,9 @@ fastify.listen(0, function (err) { t.deepEqual(JSON.parse(body), { hello: 'world' }) }) }) -}) - -test('path can be specified in place of uri', t => { - t.plan(3) - fastify.listen(0, function (err) { - if (err) t.error(err) - fastify.server.unref() + test('path can be specified in place of uri', t => { + t.plan(3) fastify.route({ method: 'GET',