heroiclabs / nakama-js

JavaScript client for Nakama server written in TypeScript.
https://heroiclabs.com/docs/nakama/client-libraries/javascript/
Apache License 2.0
182 stars 54 forks source link

only close adapter if it is open #196

Closed thegoldenmule closed 1 week ago

thegoldenmule commented 2 weeks ago

We are seeing errors in production where this code in socket.ts:

this.adapter.onError = (evt) => {
        reject(evt);
        this.adapter.close();
};

Calls this:

close() {
    this._socket.close();
    this._socket = void 0;
}

But this._socket is undefined and throws an error. This throws a TypeError inside of a Promise constructor, which is then unhandled because the promise is already rejected. This can be demonstrated very succinctly with this bit of code:

const foo = () => new Promise((res, rej) => {
  rej('Error A');

  throw new Error('Error B');
});

const run = async () => {
  try {
    await foo();
  } catch(error) {
    console.log('Caught an error: ' + error);
  }
};

run();

This will output: Caught an error: Error A, whereas Error B cannot be handled.

To fix this, mirroring all other calls to this.adapter.close(), we simply need to wrap with a check that the adapter is indeed open.

CLAassistant commented 2 weeks ago

CLA assistant check
All committers have signed the CLA.

thegoldenmule commented 1 week ago

Pinging @lugehorsam for visibility.