Unexpected EncodeSchemaError and hard to find where tis the problem(solved)

Hi everyone,

I have used colyseus to build some basic game, and recently I found out that my colyseus server sometimes (not that often, maybe 2-3times a week) crashed with an error a 'Player' was expected, but 'ArraySchema' was provided in ArraySchema#1. To find out where is the problem. I have wrapped almost all of my code with Try/Catch but this still happens sometime. It seems this is happened when colyseus is broadcasting room states? Sadly I cannot find a way to reproduce this error or even catch this error in JS.

I have read several post here and some issue on github, and have updated @colyseus/schema to latest version. It seems that I cannot find a way to solve this problem.

Error: a 'Player' was expected, but 'ArraySchema' was provided in ArraySchema#1
    at new EncodeSchemaError (/home/ubuntu/back-colyseus/node_modules/@colyseus/schema/build/cjs/index.js:2231:42)
    at assertInstanceType (/home/ubuntu/back-colyseus/node_modules/@colyseus/schema/build/cjs/index.js:2270:15)
    at MyRoomState.Schema.encode (/home/ubuntu/back-colyseus/node_modules/@colyseus/schema/build/cjs/index.js:2669:21)
    at SchemaSerializer.applyPatches (/home/ubuntu/back-colyseus/node_modules/@colyseus/core/build/serializer/SchemaSerializer.js:38:40)
    at MyRoom.broadcastPatch (/home/ubuntu/back-colyseus/node_modules/@colyseus/core/build/Room.js:210:45)
    at Timeout._onTimeout (/home/ubuntu/back-colyseus/node_modules/@colyseus/core/build/Room.js:116:58)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)

HI @Alan-Jin, by the error message it seems like you're trying to add an Array item into the Array of players instead of a Player instance. The error is going to be thrown only at the next patch, that's why wrapping try/catch during assignments/pushes it doesn't catch it.

I suggest inspecting what's being added to the array.

if (item instanceof Player) {
  console.log("good!")
} else {
  console.log("will throw an error during encoding!")
}

Hope this helps, cheers!

Hi @endel,

Thank you so much! I've never thought about that (as I totally forgot that typescript will not find this problem)! After adding that if statement it seems the whole problem is solved. Really appreciate your help!