Node.jsのchild_process
モジュールのfork
で起動した子プロセスにて、例外が発生したとき、その例外を親プロセスに送る方法です。
const { fork } = require('child_process')
if (process.send) {
// 子プロセスの処理
process.on('uncaughtException', error => {
process.send(error) // 例外はメッセージとして送る
process.exit(1)
})
throw new Error('Something wrong')
} else {
// 親プロセスの処理
const childProcess = fork(__filename, [], {
serialization: 'advanced' // このオプションが必須
})
// 例外はメッセージとして受け取る
childProcess.on('message', message => {
if (message instanceof Error) {
console.log('Child process error:')
console.error(message)
}
})
}