From 1004d205d81dd60dab1dc4ef968e30d285d758df Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Wed, 25 Jan 2017 09:04:25 -0800 Subject: [PATCH] Add spec for unhandledRejection event in main process --- spec/node-spec.js | 9 ++++++++- spec/static/main.js | 30 +++++++++++++++++++++++------- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/spec/node-spec.js b/spec/node-spec.js index d366a53674a8..92c95214f957 100644 --- a/spec/node-spec.js +++ b/spec/node-spec.js @@ -131,7 +131,7 @@ describe('node feature', function () { }) describe('error thrown in renderer process node context', function () { - it('gets emitted as an process uncaughtException event', function (done) { + it('gets emitted as a process uncaughtException event', function (done) { const error = new Error('boo!') const listeners = process.listeners('uncaughtException') process.removeAllListeners('uncaughtException') @@ -156,6 +156,13 @@ describe('node feature', function () { }) }) + describe('promise rejection in main process node context', function () { + it('gets emitted as a process unhandledRejection event', function () { + const error = ipcRenderer.sendSync('handle-unhandled-rejection', 'hello') + assert.equal(error, 'hello') + }) + }) + describe('setTimeout called under Chromium event loop in browser process', function () { it('can be scheduled in time', function (done) { remote.getGlobal('setTimeout')(done, 0) diff --git a/spec/static/main.js b/spec/static/main.js index 1454641ed491..f29bd00e68b8 100644 --- a/spec/static/main.js +++ b/spec/static/main.js @@ -275,16 +275,32 @@ ipcMain.on('try-emit-web-contents-event', (event, id, eventName) => { }) ipcMain.on('handle-uncaught-exception', (event, message) => { - const listeners = process.listeners('uncaughtException') - process.removeAllListeners('uncaughtException') - process.on('uncaughtException', (error) => { - process.removeAllListeners('uncaughtException') - listeners.forEach((listener) => { - process.on('uncaughtException', listener) - }) + suspendListeners(process, 'uncaughtException', (error) => { event.returnValue = error.message }) fs.readFile(__filename, () => { throw new Error(message) }) }) + +ipcMain.on('handle-unhandled-rejection', (event, message) => { + suspendListeners(process, 'unhandledRejection', (error) => { + event.returnValue = error.message + }) + fs.readFile(__filename, () => { + Promise.reject(new Error(message)) + }) +}) + +// Suspend listeners until the next event and then restore them +const suspendListeners = (emitter, eventName, callback) => { + const listeners = emitter.listeners(eventName) + emitter.removeAllListeners(eventName) + emitter.once(eventName, (...args) => { + emitter.removeAllListeners(eventName) + listeners.forEach((listener) => { + emitter.on(eventName, listener) + }) + callback(...args) + }) +}