Skip to content

Commit

Permalink
Improved error handling for child processes (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
osyrisrblx authored Oct 15, 2023
1 parent c5486ff commit f179630
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
21 changes: 12 additions & 9 deletions src/commands/init.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { exec, ExecException } from "child_process";
import { spawn } from "child_process";
import fs from "fs-extra";
import kleur from "kleur";
import { lookpath } from "lookpath";
Expand Down Expand Up @@ -64,14 +64,17 @@ const packageManagerCommands: {

function cmd(cmdStr: string, cwd: string) {
return new Promise<string>((resolve, reject) => {
exec(cmdStr, { cwd }, (error, stdout) => {
if (error) {
reject(error);
}
resolve(stdout);
});
}).catch((error: ExecException) => {
throw new InitError(`Command "${error.cmd}" exited with code ${error.code}\n\n${error.message}`);
const [command, ...args] = cmdStr.split(" ");
const childProcess = spawn(command, args, { cwd });
let output = "";
childProcess.stdout.on("data", data => (output += data));
childProcess.stderr.on("data", data => (output += data));
childProcess.on("close", code =>
code === 0
? resolve(output)
: reject(new InitError(`Command "${cmdStr}" exited with code ${code}\n\n${output}`)),
);
childProcess.on("error", reject);
});
}

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ yargs
})
.parseAsync()
.catch(e => {
process.exitCode = 1;
if (e instanceof LoggableError) {
e.log();
} else {
Expand Down

0 comments on commit f179630

Please sign in to comment.