discord.js: Unhandled 'error' event: "WebSocket was closed before the connection was established" when client was connected and network goes down

Which package is this bug report for?

discord.js

Issue description

Steps to reproduce:

  1. Create a very simple bot like the code sample below
  2. Let the bot connect to discord
  3. Destroy the network/internet connection of the machine running the script (e.g. unplug the (virtual) network cable)
  4. Wait until the bot tries to reconnect
  5. See the app crashes on an unhandled ‘error’ event
Error: WebSocket was closed before the connection was established
    at WebSocket.close (/home/peter/tmp/node_modules/ws/lib/websocket.js:285:14)
    at WebSocketShard.destroy (/home/peter/tmp/node_modules/discord.js/src/client/websocket/WebSocketShard.js:728:27)
    at Timeout.<anonymous> (/home/peter/tmp/node_modules/discord.js/src/client/websocket/WebSocketShard.js:522:12)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
Emitted 'error' event on WebSocket instance at:
    at emitErrorAndClose (/home/peter/tmp/node_modules/ws/lib/websocket.js:984:13)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Full log: log.txt

There seams to be no way to handle the WebSocket error event.

Expected behavior would be, that discord.js keeps trying to reestablish the connection, or that there is some chance to handle the error.

Came up with this, as my internet connection was gone away and my application using discord.js crashed with the above error.

Code sample

const { Client, Intents } = require('discord.js');

const token = 'xxx';

async function main () {
  const client = new Client({
    intents: [
      Intents.FLAGS.GUILDS,
    ],
  });

  client.on('debug', console.debug);
  client.on('warn', console.warn);
  client.on('error', console.error);

  client.on('ready', () => console.log('ready'));

  await client.login(token);
}

main();

Package version

13.7.0

Node.js version

16.14.2

Operating system

Debian 10

Priority this issue should have

Medium (should be fixed soon)

Which partials do you have configured?

No Partials

Which gateway intents are you subscribing to?

Guilds

I have tested this issue on a development release

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 26 (14 by maintainers)

Most upvoted comments

@legendhimslef Using your PR #7581 seams to work fine. The error then gets emitted as shardError and a reconnect is queued. 👍

@pedroricardo Additionally to the thing above, please also have an error handler like I showed.

The stacktrace suggests that you are running 13.4.0 (or even older): Please make sure you are actually running 13.9.2 where this issue should no longer occur.