语境
我想在我的网站后端执行命令行调用。如果此命令行调用失败,我想捕获错误并引发新的自定义错误。
我尝试抛出错误如下:
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)