簡體   English   中英

是否會在node.js http.request中的“ http.IncomingMessage”上發出“錯誤”事件?

[英]Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request?

調用http.get(url, cb)時,我可以創建4種錯誤情況:

httpThrows()

可以使用錯誤的url格式或錯誤的回調等觸發。

function httpThrows() {
    try {
        http.get("www.missing-protocol.com", res => {
            console.log(res.statusCode);
        });
    } catch (error) {
        console.log("http.get() throws an error.");
    }
}

requestError()

它是主要的錯誤處理程序,並在某些與網絡相關的問題上觸發,例如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);
    });
}

responseError()(問題)

在回調中提供http.IncomingMessage作為responseres 根據文檔,它是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);
        });
    });
}

所以這最后一個處理程序:

  1. 使用http.requesthttp.get時是否觸發過此事件?
  2. 如果是這樣,什么可以觸發事件?

以我的理解,在這種情況下最終導致錯誤的唯一方法是,如果Node或Engine出現問題,並且在這兩種情況下您都無法做很多事情。

在這種情況下,我不想處理這些情況,因為您需要檢查和維護的代碼較少。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM