Node.js handle ENOTFOUND error for http request on invalid host -


i have simple http request function followed couple of sample function calls:

var http = require('http');   function makehttprequest(host, path){     var options = {         host: host,         path: path     };      callback = function(response) {         var str = '';         //another chunk of data has been recieved, append `str`, don't use @         response.on('data', function (chunk) {             str += chunk;         });          //the whole response has been recieved, callback         response.on('end', function () {             console.log('success');         });         response.on('error', function (e) {             console.log('how function execute?');         });     }      http.request(options, callback).end(); }  makehttprequest('ec2-1-2-3-4.compute-1.amazonaws.com','thepage.html') //makehttprequest('google.com','/')//sanity check, 1 works fine 

running this, get:

events.js:72         throw er; // unhandled 'error' event               ^ error: getaddrinfo enotfound     @ errnoexception (dns.js:37:11)     @ object.onanswer [as oncomplete] (dns.js:124:16) 

i want handle in code, not have application crash. how can change http request handle better? i'm dealing spot instances on aws ec2 may come , go, , crashing application here. if host doesn't exist, want re-do request on (alive) host.

the error event on request, not response. from documentation:

if error encountered during request (be dns resolution, tcp level errors, or actual http parse errors) 'error' event emitted on returned request object.

so updated code like:

var http = require('http');  function makehttprequest(host, path){     var options = {         host: host,         path: path     };      var callback = function(response) {         var str = '';         //another chunk of data has been recieved, append `str`, don't use @         response.on('data', function (chunk) {             str += chunk;         });          //the whole response has been recieved, callback         response.on('end', function () {             console.log('success');         });     };      var req = http.request(options, callback);      req.on('error', function(error) {         console.log(error);     });      req.end(); }  makehttprequest('ec2-1-2-3-4.compute-1.amazonaws.com','thepage.html'); 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -