javascript - How to catch error on http.get - Stack Overflow

I have some http.get code that looks like thishttp.get(url, function (response) {var data = ''

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 
} 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745551234a4632587.html

相关推荐

  • javascript - How to catch error on http.get - Stack Overflow

    I have some http.get code that looks like thishttp.get(url, function (response) {var data = ''

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信