提问人:Rodrigo 提问时间:6/3/2016 最后编辑:CheesoRodrigo 更新时间:11/16/2022 访问量:5105
捕获 execSync 错误
Catching execSync errors
问:
我用来运行命令。我遇到的问题是,当抛出错误时,只需将错误记录到控制台,就无法捕获它。我尝试使用语句,但它仍然只是将错误记录到控制台。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:
答:
1赞
Shiftj
12/3/2021
#1
试试这个:
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' })
评论
0赞
DavidDr90
2/21/2022
我不认为这个解决方案会奏效......调用时会抛出异常,并且代码不会到达 return 语句execSync
评论
soffice