diff --git a/lib/http-proxy/passes/web-incoming.js b/lib/http-proxy/passes/web-incoming.js index 16a122d..2fa28d2 100644 --- a/lib/http-proxy/passes/web-incoming.js +++ b/lib/http-proxy/passes/web-incoming.js @@ -103,6 +103,10 @@ module.exports = { var forwardReq = (options.forward.protocol === 'https:' ? https : http).request( common.setupOutgoing(options.ssl || {}, options, req, 'forward') ); + + // error handler (e.g. ECONNREFUSED) + forwardReq.on('error', proxyError); + (options.buffer || req).pipe(forwardReq); if(!options.target) { return res.end(); } } @@ -138,7 +142,7 @@ module.exports = { function proxyError (err){ if (req.socket.destroyed && err.code === 'ECONNRESET') { - server.emit('econnreset', err, req, res, options.target); + server.emit('econnreset', err, req, res, options.target || options.forward); return proxyReq.abort(); } diff --git a/test/lib-http-proxy-passes-web-incoming-test.js b/test/lib-http-proxy-passes-web-incoming-test.js index a89fc23..1996276 100644 --- a/test/lib-http-proxy-passes-web-incoming-test.js +++ b/test/lib-http-proxy-passes-web-incoming-test.js @@ -177,6 +177,35 @@ describe('#createProxyServer.web() using own http server', function () { }, function() {}).end(); }); + it('should forward the request and handle error via event listener', function(done) { + var proxy = httpProxy.createProxyServer({ + forward: 'http://127.0.0.1:8080' + }); + + var proxyServer = http.createServer(requestHandler); + + function requestHandler(req, res) { + proxy.once('error', function (err, errReq, errRes) { + proxyServer.close(); + expect(err).to.be.an(Error); + expect(errReq).to.be.equal(req); + expect(errRes).to.be.equal(res); + expect(err.code).to.be('ECONNREFUSED'); + done(); + }); + + proxy.web(req, res); + } + + proxyServer.listen('8083'); + + http.request({ + hostname: '127.0.0.1', + port: '8083', + method: 'GET', + }, function() {}).end(); + }); + it('should proxy the request and handle timeout error (proxyTimeout)', function(done) { var proxy = httpProxy.createProxyServer({ target: 'http://127.0.0.1:45000',