diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js index ec8a27612d5826..3b8356e2859ef0 100644 --- a/lib/internal/main/worker_thread.js +++ b/lib/internal/main/worker_thread.js @@ -199,10 +199,12 @@ port.on('message', (message) => { function workerOnGlobalUncaughtException(error, fromPromise) { debug(`[${threadId}] gets uncaught exception`); let handled = false; + let handlerThrew = false; try { handled = onGlobalUncaughtException(error, fromPromise); } catch (e) { error = e; + handlerThrew = true; } debug(`[${threadId}] uncaught exception handled = ${handled}`); @@ -210,6 +212,16 @@ function workerOnGlobalUncaughtException(error, fromPromise) { return true; } + if (!process._exiting) { + try { + process._exiting = true; + process.exitCode = handlerThrew ? 7 : 1; + if (!handlerThrew) { + process.emit('exit', process.exitCode); + } + } catch {} + } + let serialized; try { const { serializeError } = require('internal/error_serdes'); diff --git a/test/fixtures/process-exit-code-cases.js b/test/fixtures/process-exit-code-cases.js index c8c4a2ebe6c7ff..3f1a4145b57ca9 100644 --- a/test/fixtures/process-exit-code-cases.js +++ b/test/fixtures/process-exit-code-cases.js @@ -111,3 +111,15 @@ cases.push({ result: 0, error: /^Error: ok$/, }); + +function exitWithThrowInUncaughtHandler() { + process.on('uncaughtException', () => { + throw new Error('ok') + }); + throw new Error('bad'); +} +cases.push({ + func: exitWithThrowInUncaughtHandler, + result: 7, + error: /^Error: ok$/, +});