From 8546a57a1c19f00612304f2c7d8269ec9cdee82e Mon Sep 17 00:00:00 2001 From: Jeremiah Senkpiel Date: Fri, 25 Jan 2019 14:24:34 -0800 Subject: [PATCH] process: add process.triggerFatalException() Adds a public way to access `node::FatalException` from javascript, as `process.triggerFatalException()`. If an error stack is available on the value, this method of exiting does not add additional context, unlike regular re-throwing, yet also uses the regular error printing logic. This behavior is particularly desirable when doing 'fatal exits' from the unhandledRejection event. PR-URL: https://github.com/nodejs/node/pull/25715 --- doc/api/process.md | 40 ++++++++++++++++++++ lib/internal/bootstrap/node.js | 5 +++ lib/internal/modules/cjs/loader.js | 2 +- lib/internal/process/promises.js | 5 +-- lib/internal/process/task_queues.js | 5 +-- src/node_process_methods.cc | 15 ++++++++ src/node_task_queue.cc | 15 -------- test/message/process-exit-with-exception.js | 12 ++++++ test/message/process-exit-with-exception.out | 12 ++++++ 9 files changed, 89 insertions(+), 22 deletions(-) create mode 100644 test/message/process-exit-with-exception.js create mode 100644 test/message/process-exit-with-exception.out diff --git a/doc/api/process.md b/doc/api/process.md index c868f01fa1d3e8..cf118b876d5a46 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -1177,6 +1177,44 @@ a code. Specifying a code to [`process.exit(code)`][`process.exit()`] will override any previous setting of `process.exitCode`. +## process.exitWithException(error[, fromPromise]) + + +* `error` {any} +* `fromPromise` {boolean} + +Exit with the provided error value as if it was thrown from its original +context. This allows an error to re-enter Node.js's error logic unmodified, +and will use the default formatted error printing. + +If an error stack is available on the value, this method of exiting does not add +additional context, unlike re-throwing using [`throw`][]. + +This method is particularly useful when listening to the +[`'unhandledRejection'`][] process event. + +As an example: +```js +process.on('unhandledRejection', (err) => { + process.exitWithException(err); +}); + +Promise.reject(new Error('uh oh')); +``` + +Outputs something similar to the following, as is often desirable: +```console +throw.js:5 +Promise.reject(new Error('uh oh')); + ^ + +Error: uh oh + at Object. (throw.js:5:16) + +``` + ## process.getegid()