我使用打字稿调用外部进程,如下所示:
import { execSync } from 'child_process'
execSync('/my/executable/here')
但是可执行文件中有一个错误,这导致execSync失败。有没有办法捕获错误(作为字符串)并将其打印或分配给变量?
我尝试这样做,但是代码仍然不断说“ unhandledRejection承诺”
let promise = new Promise((resolve, reject) => {
execSync('/my/executable/here')
})
promise.then(result => console.log('CALL RAN'))
promise.catch(error => console.log('FOUND ERROR'))
我得到的错误看起来像这样:
2019-11-26T00:17:23.060 ERROR (pid:36622) [server] - unhandledRejection Promise {
<rejected> Error: Command failed: /my/executable/here
答案 0 :(得分:1)
您需要捕获错误,然后根据需要解决/拒绝。
例如
// Try to use const where possible
const promise = new Promise((resolve, reject) => {
try {
execSync('/my/executable/here');
resolve();
} catch(e) {
reject(e);
}
})
// Chain the promise handlers
promise
.then(result => console.log('CALL RAN'))
.catch(error => console.log('FOUND ERROR'));