Skip to content

Commit 1004d20

Browse files
committed
Add spec for unhandledRejection event in main process
1 parent 24fb560 commit 1004d20

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

spec/node-spec.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ describe('node feature', function () {
131131
})
132132

133133
describe('error thrown in renderer process node context', function () {
134-
it('gets emitted as an process uncaughtException event', function (done) {
134+
it('gets emitted as a process uncaughtException event', function (done) {
135135
const error = new Error('boo!')
136136
const listeners = process.listeners('uncaughtException')
137137
process.removeAllListeners('uncaughtException')
@@ -156,6 +156,13 @@ describe('node feature', function () {
156156
})
157157
})
158158

159+
describe('promise rejection in main process node context', function () {
160+
it('gets emitted as a process unhandledRejection event', function () {
161+
const error = ipcRenderer.sendSync('handle-unhandled-rejection', 'hello')
162+
assert.equal(error, 'hello')
163+
})
164+
})
165+
159166
describe('setTimeout called under Chromium event loop in browser process', function () {
160167
it('can be scheduled in time', function (done) {
161168
remote.getGlobal('setTimeout')(done, 0)

spec/static/main.js

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -275,16 +275,32 @@ ipcMain.on('try-emit-web-contents-event', (event, id, eventName) => {
275275
})
276276

277277
ipcMain.on('handle-uncaught-exception', (event, message) => {
278-
const listeners = process.listeners('uncaughtException')
279-
process.removeAllListeners('uncaughtException')
280-
process.on('uncaughtException', (error) => {
281-
process.removeAllListeners('uncaughtException')
282-
listeners.forEach((listener) => {
283-
process.on('uncaughtException', listener)
284-
})
278+
suspendListeners(process, 'uncaughtException', (error) => {
285279
event.returnValue = error.message
286280
})
287281
fs.readFile(__filename, () => {
288282
throw new Error(message)
289283
})
290284
})
285+
286+
ipcMain.on('handle-unhandled-rejection', (event, message) => {
287+
suspendListeners(process, 'unhandledRejection', (error) => {
288+
event.returnValue = error.message
289+
})
290+
fs.readFile(__filename, () => {
291+
Promise.reject(new Error(message))
292+
})
293+
})
294+
295+
// Suspend listeners until the next event and then restore them
296+
const suspendListeners = (emitter, eventName, callback) => {
297+
const listeners = emitter.listeners(eventName)
298+
emitter.removeAllListeners(eventName)
299+
emitter.once(eventName, (...args) => {
300+
emitter.removeAllListeners(eventName)
301+
listeners.forEach((listener) => {
302+
emitter.on(eventName, listener)
303+
})
304+
callback(...args)
305+
})
306+
}

0 commit comments

Comments
 (0)