title: Node.js http get request error event not picking up 404 or 403
body: <p>I'm making an HTTP GET request for an image. Sometimes images come back as 404 or 403.  I was surprised I had to explicitly check for that rather than picking that up in the error event. Is that how it works or am I missing something here?</p>
  
  <pre><code>function processRequest(req, res, next, url) {
      var httpOptions = {
          hostname: host,
          path: url,
          port: port,
          method: 'GET'
      };
  
      var reqGet = http.request(httpOptions, function (response) {
          var statusCode = response.statusCode;
  
          // Many images come back as 404/403 so check explicitly
          if (statusCode === 404 || statusCode === 403) {
              // Send default image if error
              var file = 'img/user.png';
              fs.stat(file, function (err, stat) {
                  var img = fs.readFileSync(file);
                  res.contentType = 'image/png';
                  res.contentLength = stat.size;
                  res.end(img, 'binary');
              });
  
          } else {
              var idx = 0;
              var len = parseInt(response.header("Content-Length"));
              var body = new Buffer(len);
  
              response.setEncoding('binary');
  
              response.on('data', function (chunk) {
                  body.write(chunk, idx, "binary");
                  idx += chunk.length;
              });
  
              response.on('end', function () {
                  res.contentType = 'image/jpg';
                  res.send(body);
              });
  
          }
      });
  
      reqGet.on('error', function (e) {
          // Send default image if error
          var file = 'img/user.png';
          fs.stat(file, function (err, stat) {
              var img = fs.readFileSync(file);
              res.contentType = 'image/png';
              res.contentLength = stat.size;
              res.end(img, 'binary');
          });
      });
  
      reqGet.end();
  
      return next();
  }
  </code></pre>