gpt4 book ai didi

javascript - 捕获 execSync 错误

转载 作者:行者123 更新时间:2023-12-05 00:29:57 36 4
gpt4 key购买 nike

我正在使用 execSync运行 soffice命令。我遇到的问题是抛出错误 execSync只需将错误记录到控制台,就无法捕获它。我试过使用 try catch声明,但它仍然只是将错误记录到控制台。

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");

我运行它并取回它:
Error: source file could not be loaded
res:

请注意我的 catch 语句是如何从未被记录的,即使一个错误被明确抛出但另一个 Error:消息会自动记录,因为我没有记录。

最佳答案

尝试这个:

function myExecSync(command, trim = true, cwd = pwd, opts = {}) {
const ret = execSync(command, { cwd, ...opts }).toString('utf-8');
return trim ? ret.trim() : ret;
}
并手动编写 stdio: 'pipe' 以防止 childprocess.stderr 输出到控制台。喜欢
myExecSync(command, true, cwd, { stdio: 'pipe' })

关于javascript - 捕获 execSync 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37597075/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com