考慮以下在執行的NodeJS JavaScript代碼:的NodeJS:http.ClientRequest在特定情況下觸發錯誤事件兩次
// 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和aft呃異常被捕獲,ECONNRESET。
如果我們在http.ClientRequest錯誤處理程序中使用nextTick或setTimeout例如異步執行回調,則不會發生這種情況。這一變化給了預期的行爲:
req.on('error', function(e) {
console.log(e);
process.nextTick(cb);
});
誰能解釋爲什麼發生這種情況,如果這是一個錯誤或按預期工作?行爲在最新的節點4.x和節點6.x中是相同的。
謝謝!