小编leo*_*org的帖子

无法捕获子进程执行回调函数的错误

语境

我想在我的网站后端执行命令行调用。如果此命令行调用失败,我想捕获错误并引发新的自定义错误。

我尝试抛出错误如下:

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

  result.on('error', (error) => {
    console.log(error.message);
    throw error;
  });
}
Run Code Online (Sandbox Code Playgroud)

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

并像这样抓住它:

try {
  await someFunction();
} catch (e) {
  ...
  throw new Error('Meaningfull error')
}
Run Code Online (Sandbox Code Playgroud)

问题

但代码永远不会到达 catch 块,因为它会在我到达抛出错误时关闭。

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 …
Run Code Online (Sandbox Code Playgroud)

javascript exec node.js restify typescript

0
推荐指数
1
解决办法
1890
查看次数

标签 统计

exec ×1

javascript ×1

node.js ×1

restify ×1

typescript ×1