In my app, I need to spawn a debugger process given a dump file to debug, say "example.dmp". If the dump file is not found or not it is not a dump file. The process will be successfully spawned but it will exit immediately. I would like to throw an error message in an async function which can be try catched later.
const spawnDebuggerProcess = (debuggerConfigs) => {
let debuggerProcess = spawn(config.debuggerName, debuggerConfigs)
debuggerProcess.on('exit', (code, signal) => {
console.log('pid ' + `${debuggerProcess.pid}`)
console.log('child process exited with ' + `code ${code} and signal ${signal}`)
})
debuggerProcess.on('error', (error) => {})
if (debuggerProcess.pid !== undefined) {
return debuggerProcess
}
throw externalError.createError({
name: externalError.SPAWN_DEBUGGER_PROCESS_ERROR,
description: 'Failed to spawn debugging process'
})
}
One of my thought is to time give this function a time window before returning. If the process exited before the time window I should throw an error. But since node.js is async. I don't have an idea of how can this be realized. Thanks!
==== EDIT =====
const spawnDebuggerProcess = async (debuggerConfigs) => {
let debuggerProcess = spawn(config.debuggerProcess.debuggerName, debuggerConfigs)
/** added a flag */
let exited = false
debuggerProcess.on('exit', (code, signal) => {
console.log('pid ' + `${debuggerProcess.pid}`)
console.log('child process exited with ' + `code ${code} and signal ${signal}`)
/** set flag to true if exited */
exited = true
})
debuggerProcess.on('error', (error) => {})
if (debuggerProcess.pid !== undefined) {
/** delay this promise for a certain amount of time, act as the time window */
await delay(config.debuggerProcess.immediateExitDelay)
/** check the flag */
if (exited) {
throw externalError.createError({
name: externalError.SPAWN_DEBUGGER_PROCESS_ERROR,
description: 'Process exited immediately'
})
}
return debuggerProcess
}
throw externalError.createError({
name: externalError.SPAWN_DEBUGGER_PROCESS_ERROR,
description: 'Failed to spawn debugging process'
})
}
It seems to be working, but I am not sure if it is a good practice.