【问题标题】:Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request?是否会在 node.js http.request 中的“http.IncomingMessage”上发出“错误”事件?
【发布时间】:2018-12-09 09:52:32
【问题描述】:

调用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");
    });
}

errorCode()

服务器响应正常,因此没有网络错误(可以处理服务器错误)。

function errorCode() {
    http.get("http://httpstat.us/501", res => {
        console.log("Got error code:", res.statusCode);
    });
}

responseError()(问题)

http.IncomingMessage 在回调中作为responseres 给出。根据documentation,它是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. 如果是这样,什么可以触发事件?

【问题讨论】:

    标签: javascript node.js error-handling


    【解决方案1】:

    据我了解,在这种情况下最终出现错误的唯一方法是节点或引擎是否存在问题,并且在这两种情况下您都无能为力。

    在这种情况下,我不想处理这些情况,因为您需要审查和维护的代码更少。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-02
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多