Skip to content

Instantly share code, notes, and snippets.

@cowboyd
Last active June 23, 2020 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboyd/34179d445eb99aebd334c031fb07490a to your computer and use it in GitHub Desktop.
Save cowboyd/34179d445eb99aebd334c031fb07490a to your computer and use it in GitHub Desktop.
catch exceptions in async computations
function* runCommand({
pkg,
command,
cwd,
pkgPath,
log = `running command for ${pkg}`,
}) {
try {
yield function*() {
console.log(log);
let response = "";
let child = yield ChildProcess.spawn(command, [], {
cwd: path.join(cwd, pkgPath),
shell: process.env.shell || true,
stdio: "pipe",
windowsHide: true,
});
yield throwOnErrorEvent(child);
let resEvents = yield on(child.stdout, "data");
while (response === "" || response === "undefined") {
try {
let data = yield resEvents.next();
response += !data.value
? data.toString().trim()
: data.value.toString().trim();
} catch (e) {}
}
const exit = yield once(child, "exit");
if (exit[1] !== null) {
console.log(exit);
throw { value: exit[0], message: exit[1] };
}
return response;
}
} catch (error) {
//if `child` fails, the error can be caught here.
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment