【发布时间】:2016-12-26 10:54:56
【问题描述】:
考虑以下在 nodejs 中执行的 javascript 代码:
// create ClientRequest
// port 55555 is not opened
var req = require('http').request('http://localhost:55555', function() {
console.log('should be never reached');
});
function cb() {
throw new Error();
}
req.on('error', function(e) {
console.log(e);
cb();
});
// exceptions handler
process.on('uncaughtException', function() {
console.log('exception caught. doing some async clean-up before exit...');
setTimeout(function() {
console.log('exiting');
process.exit(1);
}, 2000);
});
// send request
req.end();
预期输出:
{ Error: connect ECONNREFUSED 127.0.0.1:55555
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1081:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 55555 }
exception caught. doing some async clean-up before exit...
exiting
实际输出:
{ Error: connect ECONNREFUSED 127.0.0.1:55555
at Object.exports._errnoException (util.js:1026:11)
at exports._exceptionWithHostPort (util.js:1049:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1081:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 55555 }
exception caught. doing some async clean-up before exit...
{ Error: socket hang up
at createHangUpError (_http_client.js:252:15)
at Socket.socketCloseListener (_http_client.js:284:23)
at emitOne (events.js:101:20)
at Socket.emit (events.js:188:7)
at TCP._handle.close [as _onclose] (net.js:492:12) code: 'ECONNRESET' }
exception caught. doing some async clean-up before exit...
exiting
如您所见,http.ClientRequest(或者可能是 stream.Writable?)会触发两次错误事件,首先是 ECONNREFUSED,然后在捕获异常后,ECONNRESET。
如果我们使用 nextTick 或 setTimeout 在 http.ClientRequest 错误处理程序中异步执行回调,则不会发生这种情况,例如此更改给出了预期的行为:
req.on('error', function(e) {
console.log(e);
process.nextTick(cb);
});
谁能解释为什么会发生这种情况以及这是一个错误还是按预期工作?最新节点 4.x 和节点 6.x 中的行为相同。
谢谢!
【问题讨论】:
标签: node.js http exception error-handling