diff --git a/lib/node-http-proxy/routing-proxy.js b/lib/node-http-proxy/routing-proxy.js index 818a34e2a..085d6186e 100644 --- a/lib/node-http-proxy/routing-proxy.js +++ b/lib/node-http-proxy/routing-proxy.js @@ -51,6 +51,18 @@ var RoutingProxy = exports.RoutingProxy = function (options) { this.https = this.source.https || options.https; this.enable = options.enable; this.forward = options.forward; + + // + // Listen for 'newListener' events so that we can bind 'proxyError' + // listeners to each HttpProxy's 'proxyError' event. + // + this.on('newListener', function (evt) { + if (evt === 'proxyError' || evt === 'webSocketProxyError') { + Object.keys(self.proxies).forEach(function (key) { + self.proxies[key].on(evt, this.emit.bind(this, evt)); + }); + } + }); }; @@ -90,8 +102,12 @@ RoutingProxy.prototype.add = function (options) { }); this.proxies[key] = new HttpProxy(options); - this.proxies[key].on('proxyError', this.emit.bind(this, 'proxyError')); - this.proxies[key].on('webSocketProxyError', this.emit.bind(this, 'webSocketProxyError')); + if (this.listeners('proxyError').length > 0) { + this.proxies[key].on('proxyError', this.emit.bind(this, 'proxyError')); + } + if (this.listeners('webSocketProxyError').length > 0) { + this.proxies[key].on('webSocketProxyError', this.emit.bind(this, 'webSocketProxyError')); + } this.proxies[key].on('start', this.emit.bind(this, 'start')); this.proxies[key].on('forward', this.emit.bind(this, 'forward')); this.proxies[key].on('end', this.emit.bind(this, 'end')); @@ -188,7 +204,6 @@ RoutingProxy.prototype.proxyRequest = function (req, res, options) { if (!this.proxies[key]) { this.add(options); - } proxy = this.proxies[key];