diff --git a/lib/dgram.js b/lib/dgram.js index 19b8300e315be5..1b000b6ef85324 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -278,7 +278,7 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) { const cb = arguments.length && arguments[arguments.length - 1]; if (typeof cb === 'function') { function removeListeners() { - this.removeListener('error', removeListeners); + this.removeListener(EventEmitter.errorMonitor, removeListeners); this.removeListener('listening', onListening); } @@ -287,7 +287,7 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) { FunctionPrototypeCall(cb, this); } - this.on('error', removeListeners); + this.on(EventEmitter.errorMonitor, removeListeners); this.on('listening', onListening); } diff --git a/test/parallel/test-dgram-bind-error-callback.js b/test/parallel/test-dgram-bind-error-callback.js new file mode 100644 index 00000000000000..d5009f948228b2 --- /dev/null +++ b/test/parallel/test-dgram-bind-error-callback.js @@ -0,0 +1,23 @@ +'use strict'; +const common = require('../common'); +const assert = require('node:assert'); +const dgram = require('node:dgram'); + +// Ensure that bind errors (e.g. EADDRINUSE) are not silently swallowed +// when socket.bind() is called with a callback but without a user +// 'error' handler. + +const socket1 = dgram.createSocket('udp4'); + +socket1.bind(0, common.mustCall(() => { + const { port } = socket1.address(); + const socket2 = dgram.createSocket('udp4'); + + process.on('uncaughtException', common.mustCall((err) => { + assert.strictEqual(err.code, 'EADDRINUSE'); + socket1.close(); + socket2.close(); + })); + + socket2.bind({ port }, common.mustNotCall()); +}));