3
2

More than 3 years have passed since last update.

Node.js: 子プロセスの例外を親プロセスに送る方法

Posted at

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)
    }
  })

}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2