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
1 Answer
Reset to default 2you 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
版权声明:本文标题:javascript - How to catch error on http.get - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745551234a2662953.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论