denoland/deno · error · NodeError

ERR_SOCKET_DGRAM_NOT_CONNECTED

ERR_SOCKET_DGRAM_NOT_CONNECTED

Error message

Not connected

What it means

Socket.prototype.disconnect() only works on a socket whose connect state is CONNECTED. Any other state, including never connected and connect still in progress, throws ERR_SOCKET_DGRAM_NOT_CONNECTED. On success the state returns to DISCONNECTED.

Solutions

  1. Track the connect state with a flag set on the 'connect' event.
  2. Only call disconnect() on that flag.
  3. Wrap teardown disconnect() in try-catch so shutdown never breaks.

Example fix

// before
function shutdown() { socket.disconnect(); } // throws when never connected

// after
function shutdown() { if (isConnected) socket.disconnect(); }
Defensive patterns

Strategy: validation

Validate before calling

let connected = false;
socket.once('connect', () => { connected = true; });
socket.on('close', () => { connected = false; });
function teardown() { if (connected) socket.disconnect(); }

Try / catch

try { socket.disconnect(); } catch (e) { if (e.code === 'ERR_SOCKET_DGRAM_NOT_CONNECTED') { /* nothing to do */ } else throw e; }

Prevention

When it happens

Trigger: disconnect() called before any connect(). A second disconnect() after a successful one. disconnect() issued while the initial connect() is still pending.

Common situations: Cleanup routines that call disconnect() unconditionally on shutdown. Reset paths that run before the socket finished connecting. Idempotent teardown code written without state tracking.

Related errors


AI-assisted analysis of denoland/deno@9ad36f7a2c (2026-08-20). Data as JSON: /api/errors/61265d18556a42cf. Report an issue: GitHub.

Appendix: source

Thrown at ext/node/polyfills/dgram.ts:652

      );

      return;
    }

    ReflectApply(_connect, this, [port, address, callback]);
  }

  /**
   * A synchronous function that disassociates a connected `dgram.Socket` from
   * its remote address. Trying to call `disconnect()` on an unbound or already
   * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED`
   * exception.
   */
  disconnect() {
    const state = this[kStateSymbol];

    if (state.connectState !== CONNECT_STATE_CONNECTED) {
      throw new ERR_SOCKET_DGRAM_NOT_CONNECTED();
    }

    const err = state.handle!.disconnect();

    if (err) {
      throw errnoException(err, "connect");
    } else {
      state.connectState = CONNECT_STATE_DISCONNECTED;
    }
  }

  /**
   * Instructs the kernel to leave a multicast group at `multicastAddress`
   * using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically
   * called by the kernel when the socket is closed or the process terminates,
   * so most apps will never have reason to call this.
   *
   * If `multicastInterface` is not specified, the operating system will

View on GitHub (pinned to 9ad36f7a2c)