Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch http client request exceptions in node.js

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 the domain name isn't resolving or the request is timing out. The problem is is that those errors cause Node to crap out. I'm new to this whole asynchronous programming methodology, so I'm not sure where to put my try/catch statements.

I have an ajax call that goes to something like /check/site1. Server side that calls a function which attempts to make a connection and then return the statusCode. It's a very simple function, and I've wrapped each line in a try/catch and it never catches anything. Here it is:

function checkSite(url){     var site = http.createClient(80, url);     var request = site.request('GET', '/', {'host': url});     request.end();     return request;   } 

Even with each of those lines wrapped in a try/catch, I will still get uncaught exceptions like EHOSTUNREACH and so on. I want to be able to catch those and return that to the ajax call.

Any recommendations on what to try next?

like image 561
mattmcmanus Avatar asked Dec 01 '10 20:12

mattmcmanus


People also ask

Is it good to use try catch in node JS?

It means that you should try to avoid try/catch in hot code paths. Logic/business errors in Node are usually handled with error-first callback patterns (or Promises, or similar). Generally you'd only use try/catch if you expect programmer errors (ie. bugs), and other patterns for errors you expect.

What is HTTP createServer NodeJS?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.


1 Answers

http.createClient has been deprecated.

Here is a quick example of how to handle errors using the new http.request:

var http = require("http");  var options = {     host : "www.example.com" };  var request = http.request(options, function(req) {     ... }); request.on('error', function(err) {     // Handle error });  request.end(); 
like image 87
robertjd Avatar answered Sep 28 '22 06:09

robertjd