Skip to content

Commit

Permalink
proxy: do not throw on event binding. see nodejs/node#26463.
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Mar 6, 2019
1 parent efdecd3 commit a80af15
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
35 changes: 33 additions & 2 deletions lib/internal/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class EventProxy {
if (this.dom)
this.target[`on${name}`] = handler;
else
this.target.addListener(name, handler);
addListener(this.target, name, handler);
}
}

Expand All @@ -42,7 +42,7 @@ class EventProxy {
if (this.dom)
this.target[`on${name}`] = null;
else
this.target.removeListener(name, handler);
removeListener(this.target, name, handler);
}
}

Expand Down Expand Up @@ -104,6 +104,37 @@ class EventProxy {
}
}

/*
* Helpers
*/

function addListener(ee, name, handler) {
try {
ee.addListener(name, handler);
} catch (e) {
if (!isCloseError(name, e))
throw e;
}
}

function removeListener(ee, name, handler) {
try {
ee.removeListener(name, handler);
} catch (e) {
if (!isCloseError(name, e))
throw e;
}
}

function isCloseError(name, err) {
if (name !== 'message')
return false;

// Node throws when trying to unbind `message` from a closed port.
// See: https://github.com/nodejs/node/issues/26463
return err && err.message === 'Cannot send data on closed MessagePort';
}

/*
* Expose
*/
Expand Down
10 changes: 10 additions & 0 deletions test/threads-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -933,4 +933,14 @@ describe(`Threads (${threads.backend})`, (ctx) => {
thread.on('error', cb);
thread.on('exit', onExit(cb, () => called, 0));
});

it('should not throw on unbind after close', () => {
const {port1, port2} = new threads.Channel();
const fn = () => {};

port1.on('message', fn);
port1.close(() => {
port1.off('message', fn);
});
});
});

0 comments on commit a80af15

Please sign in to comment.