Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js unhandled "error" event

Tags:

node.js

This error randomly appears When leaving my discord bot online for too long, around 3-4 hours but sometimes the error occurs sooner and sometimes later. It's really bothering me.

  events.js:188
      throw err;
      ^

Error: Unhandled "error" event. ([object Object])
    at Client.emit (events.js:186:19)
    at WebSocketConnection.onError (D:\BasementMonster\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:374:17)
    at WebSocket.onError (D:\BasementMonster\node_modules\ws\lib\event-target.js:128:16)
    at emitOne (events.js:116:13)
    at WebSocket.emit (events.js:211:7)
    at _receiver.cleanup (D:\BasementMonster\node_modules\ws\lib\websocket.js:211:14)
    at Receiver.cleanup (D:\BasementMonster\node_modules\ws\lib\receiver.js:557:13)
    at WebSocket.finalize (D:\BasementMonster\node_modules\ws\lib\websocket.js:206:20)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
like image 634
Mxm Avatar asked Aug 12 '26 01:08

Mxm


2 Answers

I wrestled with this problem for a while in my own code. The main problem is that the trace is completely unhelpful, and that the error occurs so infrequently as to make "run it in the terminal and wait" a futile task. Eventually, I was able to figure out that the Discord.js client itself was throwing an error -- this wasn't mentioned in any of the documentation I read, so I had no handler for it -- and since this oopsie happens in the Discord.js package itself, there was no line in my code for it to point to in the trace.

What needs to exist in the code somewhere is something along the lines of

client.on('error', (err) => {
   console.log(err.message)
});

This is adjusted, of course, for whatever your Client object is, and whatever you want the error handling to be. This specific trace, as far as I can tell, comes from losing Internet connection, which is something I want to have a record of, so instead of console.log() I called my own custom function that writes the event out to a logfile with a timestamp.

Testing this by running an instance of the bot and killing my Internet connection revealed that not only did the logging function work, but that Discord.js automatically restored the bot's session after it came back. (Your mileage may vary.)

like image 168
John Smith Avatar answered Aug 14 '26 14:08

John Smith


You need to add an error handling event, like this:client.on('error', console.error);

like image 29
Archer Gu Avatar answered Aug 14 '26 14:08

Archer Gu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!