From 78838beb85ac9899acf7315757662e857209c811 Mon Sep 17 00:00:00 2001 From: SelfhostedPro Date: Mon, 15 May 2023 21:56:57 -0700 Subject: [PATCH] Update ssh.js to add error handling. Was running into an issue where I couldn't catch an error if the SSH client timed out. Adding the `.on` catch enabled me to catch it from the parent application. If it needs more changes, please let me know. For now I'm just patching it with `pnpm patch` which I would prefer not to do. --- lib/ssh.js | 51 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/lib/ssh.js b/lib/ssh.js index f650413..8d562c9 100644 --- a/lib/ssh.js +++ b/lib/ssh.js @@ -1,30 +1,43 @@ var Client = require('ssh2').Client, http = require('http'); -module.exports = function(opt) { +module.exports = function (opt) { var conn = new Client(); var agent = new http.Agent(); - agent.createConnection = function(options, fn) { - conn.once('ready', function() { - conn.exec('docker system dial-stdio', function(err, stream) { - if (err) { - conn.end(); - agent.destroy(); - return; - } + agent.createConnection = function (options, fn) { + try { + conn.once('ready', function () { + conn.exec('docker system dial-stdio', function (err, stream) { + if (err) { + handleError(err); + } - fn(null, stream); - - stream.once('close', () => { - conn.end(); - agent.destroy(); + fn(null, stream); + + stream.addListener('error', (err) => { + handleError(err); + }); + stream.once('close', () => { + conn.end(); + agent.destroy(); + }); }); - }); - }).connect(opt); - - conn.once('end', () => agent.destroy()); + }).on('error', (err) => { + handleError(err); + }) + .connect(opt); + conn.once('end', () => agent.destroy()); + return agent; + + } catch (err) { + handleError(err); + } }; - return agent; + function handleError(err) { + conn.end(); + agent.destroy(); + throw err; + } };