1

I have some proxy code like this below. Problem is that whenever the target server is down, this code fails to capture the error, resulting in the entire application crashing with Error: connect ECONNREFUSED.

For a proxy server, this is terrible, it needs to just return an error to the caller, not crash altogether upon the first time that the target server is unreachable.

What is the right way around it these days?

Node version 6.

    let targetUrl = "http://foo.com/bar"

    app.options('/cors-proxy/bar', cors())
    app.post('/cors-proxy/bar', function(req, res) {  
      console.log(`received message with method ${req.method} and some body ${req.body}`)
      console.log(`relaying message to ${targetUrl}`)
      try {
        req.pipe(
          request({
            url: targetUrl,
            method: req.method,
            json: req.body 
          })
        ).pipe(res);
      } catch (err) {
        res.status(502)
        res.render('error', {
          message: err.message,
          error: err
        });
      } 
    });

Thanks!

matanster
  • 15,072
  • 19
  • 88
  • 167

1 Answers1

1

In general, you can't use try/catch to catch exceptions that may occur in asynchronous callbacks or asynchronous operations. That will only catch synchronous errors.

Instead, you have to read how each particular asynchronous operation reports errors and make sure you are plugged into that particular mechanism.

For example, streams report errors with a message to the stream that you intercept with stream.on('error', ...). For example, a request() can report errors several different ways depending upon which request() library you are actually using and how you are using it.

Some references:

Error handling with node.js streams

Stream Readable Error

How Error Events Affect Piped Streams in Node.js

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks. Kind of what I assumed. Isn't everything but atomic statements however, asynchronous in javascript and in node.js? – matanster Jul 16 '16 at 01:13
  • @matanster - No. Lots of things are synchronous in node.js. You could execute hundreds of pages of synchronous Javascript. Things are only asynchronous when you explicitly execute an asynchronous operation and then it's only the response that is asynchronous. In your handler, the `req.pipe()`, the `request()`, the `.pipe()` and the `res.render()` are all asynchronous. When you call them, that just starts their execution, the stack clears (thus why exceptions aren't caught) and they execute in the background and complete some time later. – jfriend00 Jul 16 '16 at 01:22