1

I have the following javascript node.js code:

    var options = {
         host: "x.y.z"
        ,path: "/api/abc/"
        ,method: "GET"
    };

    var req = http.request(options);

   req.on('response' , function(data) {
      console.log("response: ",data.statusCode);
      done();
   });

   req.on('error' , function() {
      console.log("error");
      done();
   });

   req.end();

I can't get the error event when an actual HTTP request error occurs. What am I missing ?


Preliminary findings: It would appear that the failure case "no response from server" (e.g. due to network issue) does not fire any event. So, the workaround is to create a 'timer' and trap this condition by yourself.

jldupont
  • 93,734
  • 56
  • 203
  • 318
  • Your code works as is (with the `done` calls removed and `var http= require('http');` added, of course). The `error` handler is called, immediately if the error is immediate (e.g. connection refused, domain not found...), a bit later if the error takes a while (e.g. timeout). – jcaron Jan 17 '16 at 00:56

2 Answers2

0

Try using an if / else statement instead of two independent functions.

if(response you want && response.statusCode = 200){
   //logic
} else {
   //console.log("error")
}
AlexanderGriffin
  • 515
  • 2
  • 13
  • This only works when an actual response is received from a server. Many failure cases are the result of something else. – jldupont Jan 16 '16 at 20:22
  • I would need more context to look into this further than the code you provided if you aren't even getting a response from the server. – AlexanderGriffin Jan 16 '16 at 20:28
  • E.g. when there isn't a server to respond to the request, no 'error' event is triggered. In other words, how can we trap the fact that no response was received ? Do I need to setup a timer just for this ?? – jldupont Jan 16 '16 at 20:30
  • Could you write something that checks if there was any sort of status code returned at all (indicating no response) after a certain amount of time and then trigger an error if those conditions are met? – AlexanderGriffin Jan 16 '16 at 20:32
  • Yeah, I think a timer is the best approach because if there is no server to make a connection to, I don't know how else anything would return an error unless you setup a timer. – AlexanderGriffin Jan 16 '16 at 20:35
  • I would have expected this facility to be present in node's HTTP package :( – jldupont Jan 16 '16 at 20:38
0

You should create your own Timeout function inside the request. In fact, I believe that after a lot of time (maybe a minute?) the request would fail. But, if you require something more earlier, you can check this thread that asks for the same thing:

How to set a timeout on a http.request() in Node?

Community
  • 1
  • 1
Ivan Seidel
  • 2,394
  • 5
  • 32
  • 49