Home > Back-end >  Unable to catch error from childprocess exec callback function
Unable to catch error from childprocess exec callback function

Time:06-06

Context

I want to execute a comand line call in the backend of my website. If this comandline call fails, I want to catch the error and throw a new custom Error.

I tried to throw the error as follows:

async function someFunction(): Promise<void> {
  ...
  const result = exec(`some command`);

  result.on('error', (error) => {
    console.log(error.message);
    throw error;
  });
}

and

async function someFunction(): Promise<void> {
  ...
  exec(`some command`, (error) => {
    if (error) {
      throw error;
    }
  });
}

and catch it like this:

try {
  await someFunction();
} catch (e) {
  ...
  throw new Error('Meaningfull error')
}

Problem

But the code never reaches the catch block, as it shuts down the second i reacht the throw error.

Error: Command failed: some Command: Kommando nicht gefunden. //(Command not found)

    at ChildProcess.exithandler (node:child_process:398:12)
    at ChildProcess.emit (node:events:527:28)
    at ChildProcess.emit (node:domain:475:12)
    at maybeClose (node:internal/child_process:1092:16)
    at Socket.<anonymous> (node:internal/child_process:451:11)
    at Socket.emit (node:events:527:28)
    at Socket.emit (node:domain:475:12)
    at Pipe.<anonymous> (node:net:709:12) {
  code: 127,
  killed: false,
  signal: null,
  cmd: 'some Command'
}
Waiting for the debugger to disconnect...
[nodemon] app crashed - waiting for file changes before starting...

I tried removing the error handeling attempt and the app keeps on minding its own business. I don't understand why it keeps crashing when I trie to handle an error...

I am aware, that the command fails, and I don't care. I just want to be able to handle the error.

Edit 1

I also tried a try catch arround the exec call.

    try {
      exec(`some Command`, (error) => {
        if (error) {
          throw error;
        }
      });
    } catch (e) {
      throw e;
    }

But sadly the app crashes right at the throw error line.

Edit 2

I use an restify middleware based error handler

this.restify.on('uncaughtException', function(req, res, route, err) {
  res.send(500, err.message);
});

As an example. The Following code is beeing handled as expected:

if (!newUser.course) {
  console.log('no course selected');
  throw new Error('signal/no-course'); // error is thrown and handled accordingly
}

try {
  await someFunction(newUser); // error in someFunction is thrown and crashes the app...
} catch (e) {
  console.log(e);
  throw new Error('signal/add-user');
}

I also tried adding console.log(error) in every catch. Didn't help.

CodePudding user response:

Hello I think the correct way to approach this would be to wrap it into a Promise since it is an error within a callback, if you actually want to try and catch the error where it happens, it has to be done inside the callback as far as I am aware.

Possible solution:

function someFunction() {
    return new Promise((resolve, reject) => {
        exec(`some command`, (error) => {
            if (error) {
                reject(error);
            }
            resolve("coding is fun            
  • Related