diff --git a/lib/internal/process/warning.js b/lib/internal/process/warning.js index ebf4c932fa9c57..82bff2ece9e146 100644 --- a/lib/internal/process/warning.js +++ b/lib/internal/process/warning.js @@ -126,8 +126,13 @@ function emitWarning(warning, type, code, ctor) { if (warning.name === 'DeprecationWarning') { if (process.noDeprecation) return; - if (process.throwDeprecation) - throw warning; + if (process.throwDeprecation) { + // Delay throwing the error to guarantee that all former warnings were + // properly logged. + return process.nextTick(() => { + throw warning; + }); + } } process.nextTick(doEmitWarning, warning); } diff --git a/test/parallel/test-process-warning.js b/test/parallel/test-process-warning.js index e4538ddc084722..c1fbbf775fb45e 100644 --- a/test/parallel/test-process-warning.js +++ b/test/parallel/test-process-warning.js @@ -38,9 +38,14 @@ function test4() { // process.emitWarning will throw when process.throwDeprecation is true // and type is `DeprecationWarning`. process.throwDeprecation = true; - assert.throws( - () => process.emitWarning('test', 'DeprecationWarning'), - /^DeprecationWarning: test$/); + process.once('uncaughtException', (err) => { + assert.match(err.toString(), /^DeprecationWarning: test$/); + }); + try { + process.emitWarning('test', 'DeprecationWarning'); + } catch { + assert.fail('Unreachable'); + } process.throwDeprecation = false; setImmediate(test5); }