Skip to content

Commit 69cf892

Browse files
maartenthjcrugzz
authored andcommitted
Handle errors for forward request, add test case (#1099)
1 parent 2f7f037 commit 69cf892

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/http-proxy/passes/web-incoming.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,10 @@ module.exports = {
103103
var forwardReq = (options.forward.protocol === 'https:' ? https : http).request(
104104
common.setupOutgoing(options.ssl || {}, options, req, 'forward')
105105
);
106+
107+
// error handler (e.g. ECONNREFUSED)
108+
forwardReq.on('error', proxyError);
109+
106110
(options.buffer || req).pipe(forwardReq);
107111
if(!options.target) { return res.end(); }
108112
}
@@ -138,7 +142,7 @@ module.exports = {
138142

139143
function proxyError (err){
140144
if (req.socket.destroyed && err.code === 'ECONNRESET') {
141-
server.emit('econnreset', err, req, res, options.target);
145+
server.emit('econnreset', err, req, res, options.target || options.forward);
142146
return proxyReq.abort();
143147
}
144148

test/lib-http-proxy-passes-web-incoming-test.js

+29
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,35 @@ describe('#createProxyServer.web() using own http server', function () {
177177
}, function() {}).end();
178178
});
179179

180+
it('should forward the request and handle error via event listener', function(done) {
181+
var proxy = httpProxy.createProxyServer({
182+
forward: 'http://127.0.0.1:8080'
183+
});
184+
185+
var proxyServer = http.createServer(requestHandler);
186+
187+
function requestHandler(req, res) {
188+
proxy.once('error', function (err, errReq, errRes) {
189+
proxyServer.close();
190+
expect(err).to.be.an(Error);
191+
expect(errReq).to.be.equal(req);
192+
expect(errRes).to.be.equal(res);
193+
expect(err.code).to.be('ECONNREFUSED');
194+
done();
195+
});
196+
197+
proxy.web(req, res);
198+
}
199+
200+
proxyServer.listen('8083');
201+
202+
http.request({
203+
hostname: '127.0.0.1',
204+
port: '8083',
205+
method: 'GET',
206+
}, function() {}).end();
207+
});
208+
180209
it('should proxy the request and handle timeout error (proxyTimeout)', function(done) {
181210
var proxy = httpProxy.createProxyServer({
182211
target: 'http://127.0.0.1:45000',

0 commit comments

Comments
 (0)