59

我收到以下错误:

events.js:48
        throw arguments[1]; // Unhandled 'error' event
        ^
Error: socket hang up
    at createHangUpError (http.js:1091:15)
    at Socket.onend (http.js:1154:27)
    at TCP.onread (net.js:363:26)

在节点 v0.6.6 中,我的代码有多个 http.request 和 .get 调用。请提出一些方法来跟踪导致套接字挂起的原因,以及它是在哪个请求/调用上。谢谢

4

5 回答 5

44

快速而肮脏的开发解决方案

使用 longjohn,您将获得包含异步操作的长堆栈跟踪。

干净和正确的解决方案:从技术上讲,在节点中,每当你发出一个'error'事件并且没有人听它时,它就会抛出. 为了让它不抛出,在它上面放一个监听器并自己处理它。这样,您可以使用更多信息记录错误。

要为一组调用设置一个侦听器,您可以使用 并在运行时捕获其他错误。确保与 http(Server/Client) 相关的每个异步操作与代码的其他部分相比位于不同的error上下文中,域将自动侦听事件并将其传播到它自己的处理程序。所以你只听那个处理程序并获取错误数据。您还可以免费获得更多信息。(域已弃用)。

正如Mike建议的那样,您还可以设置NODE_DEBUG=net或使用strace。它们都为您提供节点在内部执行的操作。

于 2012-07-18T13:06:40.847 回答
20

此外,您可以设置NODE_DEBUG环境变量以net获取有关所有套接字正在做什么的信息。这样,您可以隔离哪个远程资源正在重置连接。

于 2014-01-30T21:39:29.360 回答
12

In addition to ftft1885's answer

http.get(url, function(res)
{
    var bodyChunks = [];

    res.on('data', function(chunk)
    {
        // Store data chunks in an array
        bodyChunks.push(chunk);
    }).on('error', function(e)
    {
        // Call callback function with the error object which comes from the response
        callback(e, null);
    }).on('end', function()
    {
        // Call callback function with the concatenated chunks parsed as a JSON object (for example)
        callback(null, JSON.parse(Buffer.concat(bodyChunks)));
    });
}).on('error', function(e) {
    // Call callback function with the error object which comes from the request
    callback(e, null);
});

When I had this "socket hang up" error, it was because I wasn't catching the requests errors.

The callback function could be anything; it all depends on the needs of your application. Here's an exemple of a callback logging data with console.log and logging errors with console.error:

function callback(error, data) {
    if (error) {
        console.error('Something went wrong!');
        console.error(error);
    }
    else {
        console.log('All went fine.');
        console.log(data);
    }
}
于 2014-12-03T10:04:57.247 回答
4

利用

req.on('error',function(err){})
于 2013-03-16T03:36:03.513 回答
0

很可能您的服务器套接字连接在所有 http.ServerResponse 对象结束之前以某种方式关闭。确保在处理传入连接之前已停止所有传入请求(传入连接与传入 HTTP 请求不同)。

于 2013-10-11T08:53:46.110 回答