我使用SSH2连接到端口22上的远程主机,它运行良好,但如果远程主机拒绝连接,sshClient发出'错误'事件,问题是即使我已处理此事件,那里抛出的UncaughtException导致节点进程崩溃;
// In file node_modules/ssh2/lib/client.js (line:295)
err.level = 'client-socket';
console.log(‘sock.on: error', JSON.stringify(err)); // I add this log for debugging
self.emit('error', err);
在我的代码中,我尝试过这样:
var SSHClient = require('ssh2').Client;
var sshClient = new SSHClient();
sshClient.on('error', function (error) {
console.error(’sshClient.on: error', JSON.stringify(error));
error.message = "this error is handled by callback of sshClient.on('error’): ” + error.message;
});
然后在运行我的应用程序后,在控制台中打印出来:
sock.on: error {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","level":"client-socket"}
sshClient.on: error {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","level":"client-socket"}
events.js:72
throw er; // Unhandled 'error' event
^
Error: this error is handled by callback of sshClient.on('error’): connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
第2步
然后我在client.js中注释了这一行:295,所以它看起来像这样:
err.level = 'client-socket';
console.log(‘sock.on: error', JSON.stringify(err)); // I add this log for debugging
// self.emit('error', err);
再次运行应用程序后,在控制台中它只打印此消息,并且进程未崩溃
sock.on: error {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","level":"client-socket"}
感谢您的帮助!