Reputation: 998
I call an external process using typescript, like this:
import { execSync } from 'child_process'
execSync('/my/executable/here')
But the executable is has an error in it, which is causing execSync to fail. Is there a way to catch the error (as a string) and print it or assign it to variable?
I tried doing this but the code still keeps saying "unhandledRejection Promise"
let promise = new Promise((resolve, reject) => {
execSync('/my/executable/here')
})
promise.then(result => console.log('CALL RAN'))
promise.catch(error => console.log('FOUND ERROR'))
The error that I get looks like this:
2019-11-26T00:17:23.060 ERROR (pid:36622) [server] - unhandledRejection Promise {
<rejected> Error: Command failed: /my/executable/here
Upvotes: 0
Views: 1112
Reputation: 1419
You need to catch the error and then resolve/reject as appropriate.
e.g.
// 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'));
Upvotes: 2