From 96a194fba4cb4cdcab809cb9e5ce9e29b1721f93 Mon Sep 17 00:00:00 2001 From: Simone Primarosa Date: Thu, 3 Aug 2017 05:34:56 -0400 Subject: [PATCH] feat: add unhandledRejectionHandler (#3) Removes handling of rejected promises from the unhandled exception handler and adds an unhandled rejection handler to replace the functionality. This allows users to distinguish between the two situations. BREAKING CHANGE: unhandledExceptionHandler no longer catches rejections. --- index.js | 8 ++++++++ readme.md | 5 +++++ test/cases/unhandled-promise.js | 4 ++-- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index e9dd0b8..6ef6893 100644 --- a/index.js +++ b/index.js @@ -149,6 +149,14 @@ add.uncaughtExceptionHandler = function (hook) { if (errHooks.length === 1) { process.once('uncaughtException', exit.bind(null, true, 1)); + } +}; + +// Add an unhandled rejection handler +add.unhandledRejectionHandler = function (hook) { + errHooks.push(hook); + + if (errHooks.length === 1) { process.once('unhandledRejection', exit.bind(null, true, 1)); } }; diff --git a/readme.md b/readme.md index 096270e..65ed130 100644 --- a/readme.md +++ b/readme.md @@ -67,6 +67,11 @@ exitHook.uncaughtExceptionHandler(err => { console.error(err); }); +// You can hook unhandled rejections with unhandledRejectionHandler() +exitHook.unhandledRejectionHandler(err => { + console.error(err); +}); + // You can add multiple uncaught error handlers // Add the second parameter (callback) to indicate async hooks exitHook.uncaughtExceptionHandler((err, callback) => { diff --git a/test/cases/unhandled-promise.js b/test/cases/unhandled-promise.js index 7f83b5e..38ad286 100644 --- a/test/cases/unhandled-promise.js +++ b/test/cases/unhandled-promise.js @@ -14,13 +14,13 @@ exitHook(function () { stub.called(); }); -exitHook.uncaughtExceptionHandler(function (err, cb) { +exitHook.unhandledRejectionHandler(function (err, cb) { setTimeout(function () { stub.called(); cb(); }, 50); if (!err || err.message !== 'test-promise') { - stub.reject(`No error passed to uncaughtExceptionHandler, or message not test-promise - ${err.message}`); + stub.reject(`No error passed to unhandledRejectionHandler, or message not test-promise - ${err.message}`); } stub.called(); });