admin管理员组

文章数量:1431426

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?

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?

Share Improve this question asked Oct 19, 2017 at 1:04 BaconJuiceBaconJuice 3,77915 gold badges59 silver badges90 bronze badges 1
  • 5 nodejs/api/http.html#http_http_get_options_callback – Aanand Kainth Commented Oct 19, 2017 at 1:11
Add a ment  | 

1 Answer 1

Reset to default 2

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 
} 

本文标签: javascriptHow to catch error on httpgetStack Overflow