Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching execSync erross

I'm using execSync to run a soffice command. The issue I'm having is when an error is thrown execSync just logs the error to the console there is no way of catching it. I've tried using a try catch statement but it still just logs the error to the console.

function convertToPdf(filepath, destpath) {
  var cmd = 'sofice command';

  try {
    var res = execSync(cmd, { encoding: 'utf8' });
  } catch (e) {
    console.log("Errors:", e);
  } 

  console.log("res:", res);
}

convertToPdf("test.docx");

I run this and get this back:

Error: source file could not be loaded
res:

Notice how my catch statement is never logged even though an error was clearly thrown but another Error: message is logged automatically because I'm not logging that.

like image 497
Rodrigo Avatar asked Jun 02 '16 16:06

Rodrigo


1 Answers

try this:

function myExecSync(command, trim = true, cwd = pwd, opts = {}) {
  const ret = execSync(command, { cwd, ...opts }).toString('utf-8');
  return trim ? ret.trim() : ret;
}

And write stdio: 'pipe' manually to prevent childprocess.stderr output to the console. like

myExecSync(command, true, cwd, { stdio: 'pipe' })
like image 184
Shiftj Avatar answered Mar 12 '23 08:03

Shiftj