[英]How can I turn a Node.js http.IncomingMessage into a Fetch Request object?
[英]Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request?
調用http.get(url, cb)
時,我可以創建4種錯誤情況:
可以使用錯誤的url格式或錯誤的回調等觸發。
function httpThrows() {
try {
http.get("www.missing-protocol.com", res => {
console.log(res.statusCode);
});
} catch (error) {
console.log("http.get() throws an error.");
}
}
它是主要的錯誤處理程序,並在某些與網絡相關的問題上觸發,例如DNS查找失敗或服務器無響應等。
function requestError() {
var req = http.get("http://some-url-that-does-not-exist.com", res => {
console.log(res.statusCode);
});
req.on("error", err => {
console.log("req.on('error') called with error");
});
}
服務器正常響應,因此沒有網絡錯誤(可以處理服務器錯誤)。
function errorCode() {
http.get("http://httpstat.us/501", res => {
console.log("Got error code:", res.statusCode);
});
}
在回調中提供http.IncomingMessage
作為response
或res
。 根據文檔,它是Readable steam
並且該蒸汽會發出error
事件。
function responseError() {
http.get("http://some-ulr-with-error-halfway-through.com/", res => {
console.log(res.statusCode);
// This will never be emitted?
res.on("error", err => {
console.log("res.on('error') called with error", err);
});
});
}
所以這最后一個處理程序:
http.request
或http.get
時是否觸發過此事件? 以我的理解,在這種情況下最終導致錯誤的唯一方法是,如果Node或Engine出現問題,並且在這兩種情況下您都無法做很多事情。
在這種情況下,我不想處理這些情況,因為您需要檢查和維護的代碼較少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.