[英]Need better Node.js http.get request error handling
我使用以下http.get()
調用來調用本地端點:
http.get({
host: 'localhost',
port: 80,
path: '/service/info?id=' + id
}, function(response) {
console.log(response);
response.setEncoding('utf8');
var data = "";
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
if(data.length > 0) {
try {
var data_object = JSON.parse(data);
} catch(e) {
return;
}
}
});
}).on("error", function (){console.log("GET request error")});
但是,如果我發送格式錯誤的請求,這將觸發HTTP 400,該請求是合成不正確等,即使response.statusCode
在function(response)
是400,這將最終的catch() response.on('end', function() {}
而不是在http.get()
上發出錯誤事件,我想知道為什么會這樣,以及我如何處理HTTP 400響應作為node.js上的錯誤。
如果catch(e)
,它會等待很長時間,直到它對客戶做出任何反應,這也很奇怪。 我希望服務器盡快響應客戶端它遇到400。
詳細說明jeremy的答案,這是檢查對我有用的狀態代碼的示例:
http.get(url, function (res) {
if (res.statusCode != 200) {
console.log("non-200 response status code:", res.statusCode);
console.log("for url:", url);
return;
}
// do something great :-)
});
response.statusCode包含狀態代碼,你可以在http.get(...,cb())中得到它,或者你可以設置一個監聽器
request.on('response', function (response) {});
可以獲取狀態代碼。 如果要取消GET,可以銷毀請求,或者根據需要處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.