How to catch http client request exceptions in node.js

后端 未结 4 426
刺人心
刺人心 2020-12-05 09:42

I\'ve got a node.js app that I want to use to check if a particular site is up and returning the proper response code. I want to be able to catch any errors that come up as

4条回答
  •  庸人自扰
    2020-12-05 10:00

    I stumbled across another solution while I was researching a similar problem. http.Client emits an 'error' event if a connection can't be established for any reason. If you handle this event then the exception won't be thrown:

    var http = require('http');
    var sys = require('sys');
    
    function checkSite(url) {
        var site = http.createClient(80, url);
        site.on('error', function(err) {
            sys.debug('unable to connect to ' + url);
        });
        var request = site.request('GET', '/', {'host': url});
        request.end();
        request.on('response', function(res) {
            sys.debug('status code: ' + res.statusCode);
        });
    }
    
    checkSite("www.google.com");
    checkSite("foo.bar.blrfl.org");
    

    Of course, the connection error and the response to the request both arrive asynchronously, meaning that simply returning the request won't work. Instead, you'd have to notify the caller of the results from within the event handlers.

提交回复
热议问题