たれぱんのびぼーろく

わたしの備忘録、生物学とプログラミングが多いかも

Node.jsプロセスの終了とそのハンドル

'exit'

process.exit()による明示的なプロセス終了、あるいはイベントループの処理終了によって発生するイベント.
'exit'発生後はイベントループを止められないので非同期処理は不可能.

  • 'rejectionHandled'
  • 'uncaughtException'
  • 'uncaughtExceptionMonitor'
  • 'unhandledRejection'

トップレベル例外

catchされない例外がトップレベルにくると、デフォルトでは stderrへstack traceをプリント + exit(1) になる.

By default, Node.js handles such exceptions by printing the stack trace to stderr and exiting with code 1, overriding any previously set process.exitCode. ref

'uncaughtException'を掴んだ場合はハンドラで上記のデフォルト動作が上書きされる.

Adding a handler for the 'uncaughtException' event overrides this default behavior. ref

'uncaughtExceptionMonitor'はexit動作は必ず行われるけどその前にhookできる.

Installing an 'uncaughtExceptionMonitor' listener does not change the behavior once an 'uncaughtException' event is emitted. ref

'unhandledRejection'はexitしないけどstderrにログを吐いてくれる。ハンドラでhookできる

process.exit()は未処理のasyncも全部吹っ飛ばしてexitするので、'uncaughtExceptionMonitor'内で非同期処理を仕込んでもhook後のexit()がすぐに動いて仕込んだasyncが処理されない (動作チェック済み)

exit()の動作:

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr. ref

異常終了の比較的ましな終わらせ方

想定外のエラー(トップレベル例外)が出た場合、プロセスは無言で死ぬ.
プロセス外からプロセス監視をかけるのが1番のやり方.
もっと楽にする場合、'uncaughtException'に独自ハンドラを仕込み、ハンドラ内で非同期込みのエラーレポートをした後に手動.exit()
こうすればエラーが残る.