Errors and close codes

A connection to a room ends with a WebSocket-style close code. Codes from 4000 to 4099 are IRT’s own; the client SDK decides from the code whether to reconnect by itself or to give up and tell the game. Everything a game sees as an error is an IrtError, whose name is one of the web’s error names, the ones fetch, WebSocket and the DOM use, so a game can branch on e.name as it would for a web API. Its code has the detail:

class IrtError extends Error {
  readonly name: IrtErrorName; // "AbortError", "TimeoutError", "NetworkError", ...; see the table below
  readonly code: number;       // a close code, an HTTP status, 422 for a call the room failed, 1000 after close(), or 0
  readonly message: string;
  readonly reason: string;     // the router's or the room's close reason, such as room.kick's, or the message the room failed a call with; "" for none
}
name code, and what it means
AbortError 0: a signal aborted the connect, call or request; 1000: room.close() before the client was ready
TimeoutError 0: a connect or call timed out; 4010
NetworkError 0: the router couldn’t be reached, or the connection dropped before a call’s reply
NotSupportedError 4000
NotAllowedError 4001, 4006, 4013, 4014; 401, 403
NotFoundError 4002; 404
QuotaExceededError 4003, 4005, 4009; 429
VersionError 4004
TypeMismatchError 4015
InvalidStateError 4011, 4012; using a client before it’s ready or after it closed
OperationError 4007; 422, a call the room rejected; any other HTTP status
code Comes from
4000 to 4099 The router or the room closed the connection; see Close codes
1000 room.close()
400 to 599 createRoom, joinByCode, listPublic and quickJoin, with the HTTP status
422 A call the room answered with an error, such as a handler that threw CallRejected; see Calls
0 No close code: the router couldn’t be reached, a timeout passed, a signal aborted, a call got no answer from the room, or the client was used before it was ready or after it closed

IrtError isn’t a DOMException, whose own numeric code means something else; check it with instanceof IrtError, then its name.

Close codes

The CloseCode export of @irtio/client and @irtio/room names them, for where one name covers several codes:

// reload-on-4004.ts
import { CloseCode, connect, defineSchema, IrtError, reloadForNewBuild } from "@irtio/client";

try {
  await connect("https://rooms.irt.io/my-game/main", { schema: defineSchema({}) });
} catch (e) {
  if (e instanceof IrtError && e.name === "VersionError") reloadForNewBuild();
  else if (e instanceof IrtError && e.code === CloseCode.Superseded) console.log("You're playing in another tab.");
  else throw e;
}
Code CloseCode name Reconnects Cause What to do
4000 VersionUnsupported NotSupportedError no The client’s protocol version isn’t one the router accepts, its first message wasn’t hello, or a message couldn’t be decoded Update @irtio/client, rebuild and deploy. The router accepts the current protocol version and the one before it
4001 TokenInvalid NotAllowedError no The player token’s signature, prj, room, exp or lifetime is wrong, its meta is over 1 KB, or there’s no token and players.guests is off Get a fresh token from your backend and connect again. Tokens last at most 24 hours, so a client that reconnects after its token expired ends here
4002 RoomNotFound NotFoundError no The project or room ID is invalid, the project doesn’t exist, or the room was never created or was deleted and players.createRooms is off, so connecting doesn’t create it. Also when the client connected on one room’s URL and asked for another project or room; the reason names both Create the room first, with createRoom, irt rooms create or the HTTP API, turn players.createRooms on, or send the player back to a room list. For the URL case, connect on the URL of the room you ask for
4003 RoomFull QuotaExceededError no The room has as many connections as its room size or its maxPlayers allows; a player already connected doesn’t count again Pick or create another room
4004 SchemaMismatch VersionError no The client’s schema hash isn’t that of its room’s build: the live build’s, or an older build’s for a room still running one. Under irt dev, and from a room on an older build, the reason gives both hashes A site client: reload, which loads the live build’s site. Anything else, such as a bot or a native client, rebuild against the live build’s schema. See Builds and deploys
4005 LimitExceeded QuotaExceededError after backoff Over 120 messages a second, a message over 64 KB, a message before welcome, the router’s send queue for this client full, or too many connections to rooms that don’t exist from one address Send less: batch inputs, use state sync instead of messages for continuous data
4006 Kicked NotAllowedError no Room code called room.kick(connection, reason?), onJoin threw, the client sent something malformed, or it sent more than 64 messages or 256 KB while its room slept Show reason if the room gave one; the player may join again. Otherwise read the room’s logs (irt logs) for an onJoin error
4007 RoomStopped OperationError no Room code threw where that stops the room, or room state grew past 32 MB. A project with no live build doesn’t get it: its rooms are the default room type with no schema, which relays messages and keeps presence and a leader until you deploy Read irt logs; fix and deploy. Connecting again wakes the room from its last room state
4008 RoomMoved none at once The room restarted: its room host crashed or drained, the router lost its link to the room host, the room moved to a new live build with rooms.buildUpdate "restart" or irt restart, or the room hibernated just as the connection opened Nothing; the client fires reconnecting, reconnects and fires open
4009 SpendingLimit QuotaExceededError no The project is suspended, over limits.maxActiveRooms or limits.maxRoomHoursPerDay, or its account is out of credit The account owner raises the limit or tops up in the dashboard
4010 WakeTimeout TimeoutError after backoff The room didn’t wake within 10 seconds, or its room state couldn’t be read Nothing; the wake isn’t cancelled and the client retries
4011 RoomHibernated InvalidStateError no Room code called room.requestHibernate() with players connected, or the room went to sleep with the project’s sleeping rooms holding limits.maxSleepingConnections connections Offer a rejoin button; connecting again wakes the room
4012 Superseded InvalidStateError no The same player ID connected to the room again, from another tab, device or process Tell the player they’re playing elsewhere. Don’t reconnect automatically, or two tabs close each other in turn
4013 Banned NotAllowedError no The player is banned from the project, at hello or when the ban arrives; see Moderation Tell the player; a ban with an expiry lifts by itself
4014 RoomBanned NotAllowedError no Room code banned the player from this room with room.ban, now or before they connected; reason is the ban’s Tell the player they can’t rejoin this room, with reason; other rooms still take them
4015 RoomTypeMismatch TypeMismatchError no The room is of another room type than the client’s type, or the live build has no such type, or the client named no type and the build has no default type; reason says which, such as the room is of type "match", not "default" or the live build has no room type "duel". A room a lobby hands off to, or one made with createRoom({ type }), is of that type, so a client connecting to it by ID passes type too Connect with the room’s type. Don’t reload: the site has the same code

Any other close reconnects with backoff: 250 ms doubling up to 10 seconds, with jitter. So does a failure to open a connection after the first one. Other closes include a dropped network (1006) and 1013, which the router sends when it isn’t ready yet or when a connection sends nothing for 5 seconds after opening, as on a stalled network. reconnectAfter(code) from @irtio/protocol returns "now", "backoff" or "never" for a code, as the SDK decides.

The client’s events say what happens, as WebSocket’s do. When the connection drops and the client reconnects, it fires reconnecting, a RoomCloseEvent with the code and reason it dropped with, and readyState is "reconnecting"; once it holds the full state again it fires open, with reconnected true. A code it doesn’t reconnect after fires close, whose error is the IrtError, sets readyState to "closed", and, before the first connection was ready, rejects connect. After room.close(), close has wasClean true and no error.

// status.ts
import { CloseCode, reloadForNewBuild, type RoomClient } from "@irtio/client";

export function showStatus(room: RoomClient, show: (text: string) => void, signal?: AbortSignal) {
  room.addEventListener("reconnecting", (e) => show(`reconnecting (${e.code})`), { signal });
  room.addEventListener("open", () => show("connected"), { signal });
  room.addEventListener(
    "close",
    ({ error }) => {
      if (!error) show("You left the room.");
      else if (error.code === CloseCode.Superseded) show("You're playing in another tab.");
      else if (error.code === CloseCode.RoomHibernated) show("The room went to sleep. Rejoin?");
      else if (error.name === "VersionError") reloadForNewBuild();
      else show(error.message);
    },
    { signal },
  );
}

Aborting signal removes the listeners, as for any EventTarget.

connect

connect resolves once the client holds the room’s full state. It throws a TypeError at once for a room URL it can’t resolve: a relative one on a page with no irt-project meta tag and no project given, or one whose path doesn’t end in a project and a room ID. Otherwise it rejects with an IrtError:

name code message
NetworkError 0 can't reach room <url>: <reason>: neither WebTransport nor WebSocket connected the first time
TimeoutError 0 connecting to room <id> took longer than <timeout> ms; the client was <readyState>: timeout, 15,000 ms by default, passed first. Waking counts toward it
AbortError 0 connecting to room <id> was aborted: the signal aborted, with its reason as reason
AbortError 1000 the client closed: room.close() was called on a RoomClient before it was ready
by code 4000 to 4099 the close code’s message, below, with the router’s reason in parentheses

The message of each close code:

Code message
4000 the router doesn't support this client SDK's protocol version; update @irtio/client
4001 the player token is invalid or expired
4002 the room doesn't exist
4003 the room is full
4004 the client's schema differs from the room build's: rebuild and redeploy the client and room together, with the reason in parentheses before the colon
4006 the room kicked this connection
4013 the player is banned from this project
4014 the player is banned from this room
4015 the room is of another room type than the client's type, or the build has no such type, with the reason in parentheses
4007 the room stopped
4009 the project is over its spending limit
4011 the room hibernated by its own request; connect again to rejoin it
others connection closed with <code>

Under irt dev and in tests the reason is more specific, such as (the project doesn't allow guests; join with a player token) after 4001.

Before the client was first ready, which await connect(...) rules out, send throws and a call rejects with an InvalidStateError, as WebSocket.send throws while connecting: send() was called before the client was ready; await connect(...) or client.ready first, and the same with calls.<name>().

Calls

room.calls.name(args, { timeout, signal }) rejects with an IrtError. When the room answered with an error, its name is OperationError, its code 422, and its reason the part after the colon, to show a player:

message When Did it run?
call <name> failed in the room: <message> The handler threw or rejected, such as with CallRejected for a game rule; <message> is its error’s message It ran and threw
call <name> failed in the room: the room has no call "<name>" The room defines no such handler No
call <name> failed in the room: the reply to <name> is <n> bytes; the limit is 65536 The handler returned more than 64 KB Yes
call <name> failed in the room: the room stopped The room had stopped No
call <name> failed: the args of <name> are invalid: <why> The args don’t match the fields of a call declared with call(fields), which the client checks before sending No, it wasn’t sent

When it got no answer from the room, its code is 0:

name message When Did it run?
TimeoutError call <name> got no reply within <timeout> ms timeout, 10,000 ms by default, passed Maybe
AbortError call <name> was aborted; it may or may not have run Its signal aborted, with the signal’s reason as reason Maybe
AbortError call <name> was aborted Its signal had aborted already No
NetworkError call <name> failed: the connection dropped; it may or may not have run The connection dropped first Maybe
NetworkError call <name> failed: the room restarted; it may or may not have run The room restarted, so the old room’s reply won’t come Maybe
NetworkError call <name> failed: the client left the room; it may or may not have run close(), a close the client doesn’t reconnect after, or a handoff after its 3 seconds of waiting for the reply Maybe
NetworkError call <name> failed: the client is reconnecting Called while the client was reconnecting No
InvalidStateError call <name> failed: the client is closed Called after the client closed No

The SDK never retries a call. Make calls that change state safe to repeat, such as by sending an ID the room checks, or ask the room what happened with another call. Errors a handler throws, other than CallRejected, are also logged in the room with the player and tick.

Room-wide requests

createRoom, joinByCode, listPublic and quickJoin throw a TypeError when there’s no project URL: no project given and no irt-project meta tag. Otherwise they reject with an IrtError whose code is the HTTP status, whose name follows it (NotAllowedError for 401 and 403, NotFoundError for 404, QuotaExceededError for 429, OperationError for the rest), and whose message is <method> <path> failed with <status>: <the router's message>. When the request didn’t complete, the code is 0: an AbortError when its signal aborted, else a NetworkError.

Status Cause
400 An invalid room ID, or meta over 1 KB
401 A token was given and is invalid, or none was given and players.guests is off
403 players.createRooms is off (createRoom, joinByCode), players.listPublic is off (listPublic) or players.quickJoin is off (quickJoin)
404 No room has the join code, or its room was deleted; or the project doesn’t exist
409 createRoom with an id that a room already has
429 Too many requests from this address, with a Retry-After header; or the project has limits.maxRooms rooms
503 Room storage is unavailable, or no join code was free; try again

See Games without a backend for how they fit together.

Data calls

Player data, collection and leaderboard calls, from room code and from the client SDK alike, reject with a DataError whose code is one of these, and whose message says what to change:

Code Cause What to do
E_INVALID A malformed call: a bad key or ID, both or neither of a value, a value over 64 KB, meta over 1 KB or not flat, a bad limit, count, cursor or period, a request over 128 KB Fix the call
E_FORBIDDEN The caller may not do it: a client reading another player’s data, writing a key not in data.player.clientWrite, reading without clientRead, listing another player’s entries under clientRead: "own" (a get of one resolves with undefined instead), writing without clientWrite: "own" or another player’s entry, or an invalid token Do it from room code, or change the settings
E_UNKNOWN The collection isn’t declared in the live build, a top, around or submit on a collection without leaderboard settings, or get, list or put on one with them Declare it in irt.config.ts, or use the right calls
E_VERSION The version given isn’t the key’s or entry’s; 0 means it must not exist Read it again and decide
E_TYPE increment on a value that isn’t a number
E_QUOTA Over a player’s 256 keys or 1 MB, a collection’s 1,000,000 entries, or the collection’s maxOwn for a client Delete something first
E_LIMIT Over 200 calls a second or 64 at once for a room, 10 a second for a client address or a player, or 30 guests a minute per address for each project Call less often; use the room’s cache for gets
E_SPENDING The project is over its spending limit, or the account is out of credit Top up or raise the limit
E_UNAVAILABLE The data service can’t be reached in 5 seconds; also from a room host too old for data calls Retry; a write may or may not have happened, so retry it with version

The router answers a client’s data call with HTTP 200 and the reply whatever its outcome, 401 for a missing or invalid token, 429 past its limits and 503 when the data service is down; the client SDK turns the last three into E_FORBIDDEN, E_LIMIT and E_UNAVAILABLE.

In the room

Room code reports errors in the room’s log, which irt logs and the dashboard show. What an error in each hook does is in the Room SDK reference: errors in onMessage, onLeave, onRequest, write handlers and call handlers cost only the message, write or call; errors in onJoin close that connection with 4006; errors anywhere else stop the room with 4007. In tests, a stopped room makes tick and advance throw a RoomStoppedError with the reason.

A room that stops on wake gives a reason that says what to change:

Reason Fix
room state is at version 1 and this build has no migration to version 2 Add migrations[2]
room state is at version 2, newer than this build's version 1 A build older than the room state is live; see Rolling back
room state has entities of kind <kind>, which this build doesn't declare; add a migration Keep the kind, or remove its entities in a migration
room state for <what> doesn't fit this build's declarations; add a migration: ... A field changed type or range; convert it in a migration
room state is <n> MB; the limit is 32 MB Store less; see Room state

Common mistakes

  • Reconnecting by hand. The SDK already reconnects after the codes that allow it. A loop that calls connect again on every close turns 4012 into two tabs fighting and 4011 into a room that can’t hibernate.
  • Reloading on every close. Reload only on 4004, a VersionError, which a new build causes; other codes don’t go away on reload.
  • Retrying a failed call blindly. It may have run. Make it safe to repeat first.
  • Treating 4001 as permanent. It’s usually an expired token: fetch a new one and connect again.