node.js distinguishing errors when making http request

后端 未结 1 1803
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 10:02

My node.js application is using http.request to the REST API http://army.gov/launch-nukes and I need to distinguish between three possible cases:

相关标签:
1条回答
  • 2021-02-02 10:30

    Here is an example:

    var http = require('http');
    
    var options = {
      hostname: 'localhost',
      port: 7777,
      path: '/',
      method: 'GET'
    };
    
    var req = http.request(options, function (res) {
      // check the returned response code
      if (('' + res.statusCode).match(/^2\d\d$/)) {
        // Request handled, happy
      } else if (('' + res.statusCode).match(/^5\d\d$/))
        // Server error, I have no idea what happend in the backend
        // but server at least returned correctly (in a HTTP protocol
        // sense) formatted response
      }
    });
    
    req.on('error', function (e) {
      // General error, i.e.
      //  - ECONNRESET - server closed the socket unexpectedly
      //  - ECONNREFUSED - server did not listen
      //  - HPE_INVALID_VERSION
      //  - HPE_INVALID_STATUS
      //  - ... (other HPE_* codes) - server returned garbage
      console.log(e);
    });
    
    req.on('timeout', function () {
      // Timeout happend. Server received request, but not handled it
      // (i.e. doesn't send any response or it took to long).
      // You don't know what happend.
      // It will emit 'error' message as well (with ECONNRESET code).
    
      console.log('timeout');
      req.abort();
    });
    
    req.setTimeout(5000);
    req.end();
    

    I recommend you play with it using netcat, ie.:

    $ nc -l 7777
    // Just listens and does not send any response (i.e. timeout)
    
    $ echo -e "HTTP/1.1 200 OK\n\n" | nc -l 7777
    // HTTP 200 OK
    
    $ echo -e "HTTP/1.1 500 Internal\n\n" | nc -l 7777
    // HTTP 500
    

    (and so on...)

    0 讨论(0)
提交回复
热议问题