Node-http-proxy: Catch proxy error?

Created on 16 Jun 2012  路  9Comments  路  Source: http-party/node-http-proxy

Is there a way to catch proxy error? I mean, if the target didn't respond or isn't availabe..
I was thinking about something like this:

var httpProxy = require('http-proxy');

httpProxy.createServer(function (req, res, proxy) {

  proxy.proxyRequest(req, res, {
    host: 'localhost',
    port: 9000
  });

  proxy.on('error', function(err, req, res){
      if(err) console.log(err);
      res.writeHead(500);
      res.end('Ooops, something went very wrong...');
  });

}).listen(80);

Most helpful comment

In this example you will see the use of proxyError event.

All 9 comments

In this example you will see the use of proxyError event.

Worked like a charm, thx.

This does not work well for the RoutingProxy.

If I get ECONNRESET from the backend server, doing res.writeHead(500) in the proxyError handler will give me the "Can't render headers after they are sent to the client." error.

Any ideas?

EDIT: Actually, the proxy already resets the connection for me, but does not give me the alternative to call res.send(500)

@alum this is expected. When you start proxying and the backend server sends the headers and _then_ breaks the connections, the headers were already proxied back to the client. You have to catch the "Can't render headers after they are sent to the client." error.

Hi, i've met this error in my proxy, i follow your guide to catch the error like this:

var proxy = new httpProxy.RoutingProxy();
proxy.on("Can\'t render headers after they are sent to the client.", function(err, req, res){
if(err) console.log(err);
res.writeHead(500);
res.end('Ooops, something went very wrong....');
});

But the proxy still throws the error, and i can't caught it.
Do you have any advice ?
THank you very much.

So it's actually not the proxy that's throwing that error, but rather the response object. Also, there is not event called "Can\'t render headers after they are sent to the client." Most events are called things like "error" or "finish".
Basically I think you need to wrap res.writeHead() in a try-catch and handle the error that way.

Hi all, is there any way to identify which backend server failed to serve the request, so that we can mark that server as down.

@arjunrp
You probably want to set up one proxy per backend server. That way you will always know which server failed and you will have a nice separation between proxies.

@alum thanks for the reply, i have got another solution
proxy.web(req, res, target, function (e) {
// check the error object and mark the target as down
});
is this the correct way to do this?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DominicTobias picture DominicTobias  路  3Comments

martindale picture martindale  路  6Comments

tbc1 picture tbc1  路  4Comments

mbret picture mbret  路  5Comments

adi518 picture adi518  路  3Comments