How to catch http client request exceptions in node.js

后端 未结 4 425
刺人心
刺人心 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:20

    Unfortunately, at the moment there's no way to catch these exceptions directly, since all the stuff happens asynchronously in the background.

    All you can do is to catch the uncaughtException's on your own:

    var http = require('http');
    
    function checkSite(url){
        var site = http.createClient(800, url);
        var request = site.request('GET', '/', {'host': url});
        request.end();
        return request;
    }
    
    process.on('uncaughtException', function (err) {
        console.log(err);
    }); 
    
    checkSite('http://127.0.0.1');
    

    Which in this case (notice port 800) logs:

    { message: 'ECONNREFUSED, Connection refused',
      stack: [Getter/Setter],
      errno: 111,
      syscall: 'connect' }
    

    Node.js is still under heavy development and there sure will be a lot of progress in the next couple of months, right now focus seem to be on fixing performance bugs for 3.x and making the API somewhat stable, because after all Node.js is mainly a server so throughput matters.

    You can file a bug though, but be warned crashes etc. have way higher priority than features, and most new features make it in via fork pull requests.

    Also for the current Roadmap of Node.js watch this talk by Ryan Dahl (Node's Creator):
    http://developer.yahoo.com/yui/theater/video.php?v=yuiconf2010-dahl

提交回复
热议问题