title: node.js distinguishing errors when making http request
body: <p>My node.js application is using <code>http.request</code> to the REST API <code>http://army.gov/launch-nukes</code> and I need to distinguish between three possible cases:</p>
  
  <ul>
  <li><code>Success</code> -- The server replies in the affirmative. I know my enemies are destroyed.</li>
  <li><code>Failure</code> -- Either I have received error from the server, <em>or was unable to connect to server</em>. I still have enemies. </li>
  <li><code>Unknown</code> -- <em>After establishing a connection to the server</em>, I have sent the request -- but not sure what happened. This could mean the request never made it to the server, or the server response to me never made it. I may or may not have just started a world war.</li>
  </ul>
  
  <p>As you can see, it's very important for me to distinguish the <code>Failure</code> and <code>Unknown</code> case, as they have very different consequences and different actions I need to take.</p>
  
  <p>I would also very much like to use http Keep-Alive -- as what can I say, I'm a bit of a war-monger and plan on making lots of requests in bursts (and then nothing for long periods of time)</p>
  
  <p>--</p>
  
  <p>The core of the question is how to separate a connection-error/time-out (which is a <code>Failure</code>) from an error/timeout that occurs after the request is put on the wire (which is an <code>Unknown</code>).</p>
  
  <p>In psuedo-code logic I want this:</p>
  
  <pre><code>var tcp = openConnectionTo('army.gov') // start a new connection, or get an kept-alive one
  tcp.on('error', FAILURE_CASE);
  tcp.on('connectionEstablished',  function (connection) {
  
         var req = connection.httpGetRequest('launch-nukes');
         req.on('timeout', UNKNOWN_CASE);
         req.on('response', /* read server response and decide FAILURE OR SUCCESS */);
     }
  )
  </code></pre>