Landon
Landon

Reputation: 4108

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

I a have a very simple http request function followed by a 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, so append it to `str`, i don't use this at all
        response.on('data', function (chunk) {
            str += chunk;
        });

        //the whole response has been recieved, do callback
        response.on('end', function () {
            console.log('success');
        });
        response.on('error', function (e) {
            console.log('how do i get this function to execute?');
        });
    }

    http.request(options, callback).end();
}

makeHttpRequest('ec2-1-2-3-4.compute-1.amazonaws.com','thepage.html')
//makeHttpRequest('google.com','/')//sanity check, this one works fine

Running this, I get:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete] (dns.js:124:16)

I want to handle this in the code, not have my application crash. How can I change my http request to handle this better? I'm dealing with spot instances on aws ec2 that may come and go, and that is crashing my application here. If that host doesn't exist, I want to re-do that request on another (alive) host.

Upvotes: 1

Views: 2567

Answers (1)

dylants
dylants

Reputation: 23350

The error event is on the request, not the response. From the documentation:

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.

So your updated code would look something 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, so append it to `str`, i don't use this at all
        response.on('data', function (chunk) {
            str += chunk;
        });

        //the whole response has been recieved, do 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');

Upvotes: 3

Related Questions