BaconJuice
BaconJuice

Reputation: 3779

How to catch error on http.get

I have some http.get code that looks like this

http.get(url, function (response) {
    var data = '';
    response.on('data', function (x) {
        data += x;
    });
    response.on('end', function () {
        var json = JSON.parse(data);
        console.log(json);
    });
});

How do I error handling this if an invalid URL/API endpoint is provided?

Upvotes: 1

Views: 10368

Answers (1)

Ahmed farag mostafa
Ahmed farag mostafa

Reputation: 2934

you can handle http.get errors by check state error example:-

http.get(url, function (response) {
        response.on('error', function (err) {
          //do some thing , error  handling
          console.log(err);
        });
    });

you can validate the url by validating response code & ping domain or url

1 - validate response code :-

http.get(url, function (response) {
   if(response.statusCode !== 200){
     //error happens
   }
    });

2- ping on the giving url using this repo valid-url:-

var validUrl = require('valid-url');

if (!validUrl.isUri('apiUrl')){
   //error not valid url 
} 

Upvotes: 2

Related Questions