Node.js处理无效主机上的http请求的ENOTFOUND错误

时间:2014-06-09 19:19:27

标签: node.js

我有一个非常简单的http请求函数,后跟几个示例函数调用:

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

运行这个,我得到:

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)

我想在代码中处理这个问题,而不是让我的应用程序崩溃。如何更改我的http请求以更好地处理此问题?我在aws ec2上处理可能来来去去的现场实例,这就是我的应用程序崩溃了。如果该主机不存在,我想在另一个(活动)主机上重新执行该请求。

1 个答案:

答案 0 :(得分:2)

error事件位于request,而不是responseFrom the documentation

  

如果在请求期间遇到任何错误(使用DNS解析,TCP级别错误或实际的HTTP解析错误),则会在返回的请求对象上发出“错误”事件。

因此,您更新的代码如下所示:

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');