Operations

Error codes

Identify Sirannon failures by code, reconcile uncertain writes, and check the HTTP status and WebSocket close codes.

The embedded engine raises subclasses of SirannonError, each with a code that a program can compare, while the network client raises RemoteError when the server refuses a call. Match on code, because the diagnostic messages can change between releases. The example below catches a failed NOT NULL constraint and closes the registry whichever error occurs.

catch-errors.ts
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { QueryError, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-errors-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
 
try {
  const db = await sirannon.open('shop', join(directory, 'shop.db'))
  await db.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, total REAL NOT NULL)')
  try {
    await db.execute('INSERT INTO orders (id) VALUES (?)', [1])
  } catch (error) {
    if (!(error instanceof QueryError)) throw error
    console.error(`SQL failed [${error.code}]: ${error.message}`, error.sql)
  }
} finally {
  try {
    await sirannon.shutdown()
  } finally {
    await rm(directory, { recursive: true, force: true })
  }
}

Some errors have fields beside the code:

  • QUERY_ERROR has sql.
  • CONFLICT_ERROR has table, rowId, and cause.
  • A migration error has version.
  • WRITE_OVERLOADED has limit and retryAfterMs.
  • SYNC_ERROR has requestId.
  • MIGRATION_REQUIRED and SCHEMA_AHEAD have serverVersion.

Every HTTP error response contains the error object below, while every WebSocket error message contains the same object beside its message type and request ID. The server adds details only when it has context that it can share.

{ "error": { "code": "ERROR_CODE", "message": "Human-readable description", "details": {} } }

A dash in a class column below means that Sirannon raises the base SirannonError with that code, so match on err.code for those codes.

Before it replies over HTTP or WebSocket, the server replaces the message of a file-opening, extension, optional-dependency, row-count, or encryption error with a fixed message that contains no file paths, and it sends no details with that message. It does the same for EXECUTION_TIMEOUT_UNSUPPORTED, BACKUP_ERROR, and BACKUP_DESTINATION_ERROR, whose messages can contain paths on the server. The server sends a fixed message without details for EXECUTION_TIMEOUT as well, because SQLite words that error differently depending on where it stops the statement. The error in the server process contains the full diagnostic context.

Core engine

ClassCodeWhen
DatabaseNotFoundErrorDATABASE_NOT_FOUNDNeither the registry nor a lifecycle resolver can provide a database for the ID.
DatabaseAlreadyExistsErrorDATABASE_ALREADY_EXISTSA caller registers an ID that another database uses.
-DATABASE_CLOSEDA caller uses a database after the database closes.
-DATABASE_OPEN_FAILEDSQLite can't open the database file, as it does when the directory of the file is missing.
ReadOnlyErrorREAD_ONLYA caller sends a write, or opens a live query, on a read-only database.
QueryErrorQUERY_ERRORSQLite fails to prepare or execute a statement, on this node or, for a forwarded write, on the primary.
-INVALID_READ_LIMITA caller passes queryWithColumns a maxRows or a maxBytes other than a whole number from 0 to 2^53-1.
-COLUMN_DETAILS_UNSUPPORTEDA caller calls queryWithColumns on a driver whose columnDetails capability is false. On Bun, a read through queryWithColumns with maxRows or maxBytes that returns two columns of the same name fails with this code too.
ForbiddenSqlErrorFORBIDDEN_SQLA statement refers to a _sirannon table, whether bare, in double quotes, backticks, or square brackets, or as a single-quoted string where SQLite reads a table name, as in FROM '_sirannon_meta'. Sirannon also raises the code for a statement that modifies the sqlite_ catalogue, uses ATTACH, DETACH, or VACUUM INTO, or uses the writable_schema, temp_store_directory, data_store_directory, or wal_checkpoint pragma. It raises the code as well for BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, and RELEASE, and for a CREATE or a DROP of a temporary table, view, index, or trigger, whether the statement is in a call or in a pending migration. Call checkpoint() in place of PRAGMA wal_checkpoint, and transaction() or executeTransaction() in place of BEGIN and COMMIT.
TransactionErrorTRANSACTION_ERROREvery statement in a transaction succeeds and SQLite then refuses the commit, as it does when a deferred foreign key fails at the commit. The error's cause contains SQLite's error.
-TRANSACTION_CLOSEDA caller uses a transaction handle after its callback returns or throws.
-WRITER_HELD_BY_CALLBACKOn wa-sqlite or Expo, a transaction callback makes a call through the database while the callback holds the writer. Use the tx handle of that callback.
HookDeniedErrorHOOK_DENIEDA before-hook rejects the operation.
RequestDeniedErrora caller-defined codeThe authenticate hook refuses the request with a caller-defined status and code.
CDCErrorCDC_ERRORThe change-data-capture pipeline fails, or Sirannon cannot use a statement for a live query.
BackupErrorBACKUP_ERRORA backup fails for a reason without a more specific code, such as a refused path or an invalid piece size.
-BACKUP_UNSUPPORTEDThe driver provides no backup engine, the connection offers no stepped copy call, the node driver uses a Node.js build whose node:sqlite exports no backup function, or a database configures backups without a file in write-ahead logging mode.
-BACKUP_RESTARTEDSQLite returns the copy to page one more times than restartLimit allows, or the copy reaches no new page across noProgressStepLimit steps.
-BACKUP_STALLEDThe copy completes no step inside stallTimeoutMs, including a copy that the writer worker stops part-way.
-BACKUP_DESTINATION_ERRORYour destination refuses a call, fails to answer inside destinationTimeoutMs, or returns pieces that do not match their chain metadata.
-BACKUP_LOG_REWOUNDThe write-ahead log restarts before a capture copies its frames, so the backup chain has a gap.
-BACKUP_CHAIN_BROKENNo full copy goes back as far as the requested moment, a chain is missing a piece that a restore needs, or no chain record has the name that the caller passes to verifyBackup.
ConnectionPoolErrorCONNECTION_POOL_ERRORThe pool is closed, exhausted, or misconfigured.
MaxDatabasesErrorMAX_DATABASESA caller opens more databases than the configured cap allows.
ExtensionErrorEXTENSION_ERRORSirannon cannot load a native SQLite extension.
-INVALID_DRIVERThe driver configuration fails validation.
-ROW_COUNTS_UNSUPPORTEDThe driver requests row counts, but the required native package or a usable counting build is missing.
ExecutionTimeoutErrorEXECUTION_TIMEOUTSQLite stops a statement at the call's executionTimeoutMs, after which Sirannon rolls back the call's transaction, so the database contains none of the call's writes. Sirannon raises the code for every later statement of that transaction as well.
-INVALID_EXECUTION_TIMEOUTA caller passes an executionTimeoutMs other than a whole number from 1 to 2,147,483,647.
-EXECUTION_TIMEOUT_UNSUPPORTEDA caller passes executionTimeoutMs on a driver whose executionTimeouts capability is false. The better-sqlite3 driver also fails open with this code under executionTimeouts: true when it can't load a build of @delali/sirannon-sqlite that interrupts statements.
-INVALID_SYNCHRONOUSA caller supplies an unknown synchronous level.
-INVALID_DURABILITYA load passes a durability other than 'off' or 'normal'.
-DURABILITY_RESTORE_FAILEDSirannon fails to restore the configured durability. It refuses later writes while restoration continues to fail.
-BULK_LOAD_IN_TRANSACTIONA transaction callback calls bulkLoad. Use tx.executeBatch to write the rows inside a transaction.
-CHECKPOINT_IN_TRANSACTIONA transaction callback calls checkpoint, which SQLite can't carry out inside a transaction, so call it once the transaction ends.
-SNAPSHOT_IN_PROGRESSA caller sends a read or a write while a device-sync snapshot load replaces the database.
-SHUTDOWNA caller starts an operation after the registry shuts down.
-SHUTDOWN_ERROROne or more databases fail to close during shutdown.
-LIFECYCLE_DISPOSEDA caller resolves a database after the application disposes the lifecycle manager.
-INTERNAL_SCHEMA_ERRORAn internal-table identifier, column type, or default fails validation, or a schema version falls outside PRAGMA user_version.

Encryption

EncryptionError extends SirannonError. The encryption guide explains key storage, file replacement, and recovery.

CodeWhen
ENCRYPTION_UNSUPPORTEDThe driver, native build, runtime, or required Expo filesystem cannot provide the requested encryption operation.
INVALID_ENCRYPTION_KEYThe loader returns something other than exactly 32 raw bytes, directly or as { key, id }.
ENCRYPTION_KEY_UNAVAILABLEThe loader throws or rejects, in which case the error's cause contains that failure.
ENCRYPTION_KEY_MISSINGA caller opens an encrypted file without a key.
ENCRYPTION_KEY_REJECTEDThe key fails to decrypt the first page, or the file uses another cipher.
DATABASE_NOT_ENCRYPTEDA caller opens a plaintext file with a key. Use changeEncryption to encrypt the file.
ENCRYPTED_PAGE_CORRUPTA later page fails authentication.
ENCRYPTION_REQUIREDA plaintext peer requests changes or a snapshot from an encrypted node.
ENCRYPTION_CHANGE_IN_PROGRESSAnother change is active, or an engine starts while a change replaces the file.
ENCRYPTION_CHANGE_ABORTEDA schema change or a write prevents an exact copy, so Sirannon goes on using the original file.

A key change can finish with state: 'done' and reopenError. Sirannon uses the new file and key from that point, so retain that key and reopen the database with it. An aborted change, by contrast, leaves the original file in use.

Writer worker

The writer worker reports a rejected write with a different code from a write whose outcome is unknown, so you can tell when a retry is safe and when you have to reconcile first.

CodeWhenRetry?
WRITE_OVERLOADEDMore writes are pending than maxPendingWrites allows, or the worker sheds a queued write when an earlier deadline expires. The server answers HTTP with 503 and Retry-After.Retry, because Sirannon never applies the write.
WRITER_WORKER_TIMEOUTThe writer reports no outcome within twice writeTimeoutMs.Retry only after you reconcile, because the outcome is indeterminate.
WRITER_WORKER_EXITThe worker crashes or exits. An active callback transaction rolls back, so later statements in that callback fail too.Reconcile an ordinary in-flight write before you retry, because the write can commit before the crash.
WRITER_WORKER_FATALThe writer passes its restart budget, so every later write fails.Restart the process, because every retry fails.
WRITER_WORKER_UNAVAILABLEA caller sends a write while no writer is available.Retry, because the write never reaches the writer.
WRITER_WORKER_CLOSEDA caller sends a write after the writer closes, or the writer closes while the write is in flight.Reconcile first when the write is in flight.
WRITER_WORKER_POST_FAILEDThe host cannot pass the operation to the writer.Retry, because the write never reaches the writer.
WRITER_WORKER_NO_PORTThe writer entry point starts outside a worker thread.Fix the configuration, because every retry fails.
WRITER_WORKER_UNSUPPORTEDA caller enables writerWorker on a driver with no worker entry, so Sirannon refuses to open the database.Change the driver or the option, because every retry fails.
INVALID_WRITER_WORKERA writerWorker value is out of range.Fix the configuration, because every retry fails.

Backups

Before you retry a backup, check the staged captures, because Sirannon removes a partial local copy once the copy operation stops. A destination that follows the contract supports safe replacement of an ordinary piece on a later capture.

CodeRetry?
BACKUP_RESTARTEDRetry once the connection that writes to the source file stops. Sirannon removes the partial file, because the copy stores nothing usable.
BACKUP_STALLEDRetry, because Sirannon removes the partial file once SQLite stops writing it.
BACKUP_DESTINATION_ERRORRetry once your storage answers again. A cycle leaves the capture staged and sends it again on a later turn automatically.
BACKUP_LOG_REWOUNDA retry fails, because the backup chain has a gap. The cycle starts a fresh chain with a full copy.
BACKUP_CHAIN_BROKENAsk for a moment that an intact chain reaches, or let the cycle start a fresh chain, because a retry of the same moment fails.
BACKUP_UNSUPPORTEDChange the driver, the runtime, or the options of the database, because every retry fails.
BACKUP_RESTORE_IN_PROGRESSRetry once the active restore finishes.
BACKUP_RESTORE_NOT_ACCEPTEDThe operator has to turn the route on with acceptBackupRestore before a retry can succeed.

Migrations

CodeWhen
MIGRATION_ERRORA migration step fails as it executes. Sirannon also raises it when a migration that turns foreign keys off leaves a row without its parent row, which PRAGMA foreign_key_check finds before the commit.
MIGRATION_VALIDATION_ERRORA migration definition fails validation, as a string migration does when it sets withoutForeignKeys and its up SQL lacks PRAGMA foreign_keys = OFF.
MIGRATION_DUPLICATE_VERSIONTwo migrations share a version.
MIGRATION_NO_DOWNA caller rolls back a migration with no down statement.
MIGRATION_SOURCE_INVALIDThe registry migration source returns something other than a list.
MIGRATION_CHECKSUM_MISMATCHAn applied migration's stored checksum differs from the checksum of its current SQL.
MIGRATION_BASELINE_GAPA history below a baseline lacks the bridging migrations.
MIGRATION_CONCURRENTConcurrent migration work prevents Sirannon from applying a migration safely.
MIGRATION_ROLLBACK_ERRORA rollback step fails.

Server and requests

CodeWhen
INVALID_REQUESTThe request body has an invalid structure, as a query body does when it sets shape to a value other than columns, sets a limit outside the range from 0 to 2^53-1, or sets maxRows or maxBytes without shape.
INVALID_JSONThe body or WebSocket message is not valid JSON.
EMPTY_BODYThe request body is empty.
PAYLOAD_TOO_LARGEThe body or message exceeds maxBodyBytes.
INTERNAL_ERRORAn unexpected error occurs while the server handles the request.
HOOK_ERRORThe authenticate hook returns a refusal object, or it throws without a valid status, code, and message. The cluster-status authoriser can raise this code as well.
NOT_FOUNDThe route does not exist, or the server has no cluster status or refuses it to the caller.
INVALID_MAX_BODY_BYTESmaxBodyBytes is not a positive integer that the transport can enforce exactly.
INVALID_WS_BACKPRESSUREmaxWebSocketBackpressureBytes fails validation or falls below maxBodyBytes.
INVALID_CLOSE_TIMEOUTserver.close receives a timeout outside the whole-number range from 0 to 2,147,483,647.
INVALID_ENCRYPTION_CHANGEYou enable key changes without authenticate or an encryptionKeys resolver.
ENCRYPTION_CHANGE_NOT_ACCEPTEDA caller reaches the change route while acceptEncryptionChange is off.
INVALID_BACKUP_RESTOREacceptBackupRestore is true and the server has no authenticate hook, so createServer refuses to create the server.
INVALID_DEVICE_SYNCacceptDeviceSync is true and the server has no authenticate hook, so createServer refuses to create the server.
BACKUP_RESTORE_NOT_ACCEPTEDA caller reaches POST /db/:id/backup/restore on a server that leaves acceptBackupRestore off.
BACKUP_RESTORE_IN_PROGRESSA restore of that database is in progress.
BULK_LOAD_UNSUPPORTEDThe execution target provides no bulk load.
INVALID_MESSAGEA WebSocket message lacks a required field or contains a value of the wrong type, as a query message does when it contains name together with shape, maxRows, or maxBytes.
UNSUPPORTED_SUBPROTOCOLA WebSocket upgrade offers subprotocols without sirannon.v1.
UNKNOWN_TYPEA WebSocket message specifies an unrecognised type.
HANDLER_CLOSEDThe WebSocket handler is shutting down.
DUPLICATE_SUBSCRIPTIONA subscription with the same ID exists on the connection.
SUBSCRIPTION_NOT_FOUNDA caller unsubscribes from a subscription that does not exist.
CDC_UNSUPPORTEDA caller subscribes to an in-memory database, because subscriptions require a file-based database.

Registered operations

These codes describe failures in registered operations.

CodeWhen
UNKNOWN_QUERYThe database has no registered operation of that name.
MISSING_ARGUMENTA declared argument is absent from the request.
ARGUMENT_NOT_ALLOWEDThe caller supplies an undeclared argument, or one that the server fills from identity.
IDENTITY_REQUIREDAn operation fills an argument from identity and the request supplies none.
REGISTRY_MISMATCHA live query sends a registry digest that differs from the digest of this server.
SQL_NOT_ACCEPTEDThe server accepts no SQL over the network, or it refuses a subscription to a table's changes because acceptSql is false and its registry has no onBeforeSubscribe hook.

Replication

@delali/sirannon-db/replication exports every class in this table. FailoverError is the shared base of NoSafePrimaryError and UnsafeRecoveryRequiredError.

ClassCodeWhen
ReplicationErrorREPLICATION_ERROREvery other class in this table extends this base class for replication failures.
SyncErrorSYNC_ERRORThe first sync fails because the node is not ready, the transfer times out, or a manifest or batch order does not match.
ConflictErrorCONFLICT_ERRORA conflict resolver throws while Sirannon applies a change. table and rowId identify the row, and cause contains the resolver's error.
TransportErrorTRANSPORT_ERRORA peer is unreachable or a send fails. A primary that refuses a forwarded write with a Sirannon code, such as QUERY_ERROR for a statement that SQLite rejects, sends that code back to the replica unchanged.
BatchValidationErrorBATCH_VALIDATION_ERRORA batch fails its checksum, breaks the schema allowlist, exceeds maxClockDriftMs, or includes unsafe DDL.
WriteConcernErrorWRITE_CONCERN_ERRORThe group does not meet the write concern inside the timeout.
ReadConcernErrorREAD_CONCERN_ERRORThe node cannot satisfy the requested read concern.
TopologyErrorTOPOLOGY_ERRORA replica refuses a write, no primary is available, a node is outside group membership, a peer is unauthorised, or a coordinator-mode configuration includes endpoint lists.
CoordinatorErrorCOORDINATOR_UNAVAILABLEThe node cannot reach the coordinator, or the coordinator cannot prove quorum authority.
AuthorityErrorAUTHORITY_LOSTA node loses primary or controller authority while it handles work.
StalePrimaryErrorSTALE_PRIMARYA request, batch, sync message, or forwarded write uses a stale primary term.
NoSafePrimaryErrorNO_SAFE_PRIMARYThe controller finds no eligible in-sync replica that it can promote safely.
NodeNotInSyncErrorNODE_NOT_IN_SYNCThe node is alive but outside the group's in-sync set.
NodeDrainingErrorNODE_DRAININGThe node is in maintenance drain mode.
ProtocolVersionMismatchErrorPROTOCOL_VERSION_MISMATCHNode compatibility metadata is incompatible with the cluster, or the group's feature level is higher than the node supports.
UnsafeRecoveryRequiredErrorUNSAFE_RECOVERY_REQUIREDRecovery requires an explicit operator action.
ReplicationErrorREPLICATION_ACTIVEA key change or restore targets a file that an active replication engine uses.

Device sync

CodeWhen
MIGRATION_REQUIREDThe device schema version is behind the server, so the device has to migrate before it syncs.
SCHEMA_AHEADThe device schema version is ahead of the server, so the server has to migrate first.
SYNC_UNSUPPORTEDThe execution target applies no changes, or the server predates device sync.
SNAPSHOT_UNSUPPORTEDA device requests a snapshot of an in-memory database.
SNAPSHOT_CHECKSUM_MISMATCHA downloaded snapshot page fails checksum verification.
DEVICE_SYNC_NOT_ACCEPTEDThe server leaves acceptDeviceSync off, so it serves no device sync. SyncController.start() raises the same code against such a server.
DEVICE_CLOCK_AHEADA pushed change has a stamp more than 300,000 milliseconds ahead of the server clock. The device stores those writes and pushes them again later.
DEVICE_NOT_SUBSCRIBEDAn acknowledgement specifies a device with no subscription on that connection.

Optional packages

Sirannon raises these codes in the local process when it starts a server, a replication transport, or a coordinator whose package it cannot load. The message identifies the missing package and the command that installs it.

CodeWhen
SERVER_DEPENDENCY_MISSINGserver.listen() cannot load uWebSockets.js.
TRANSPORT_DEPENDENCY_MISSINGThe gRPC transport cannot load @grpc/grpc-js, @bufbuild/protobuf, or grpc-health-check as the engine starts.
COORDINATOR_DEPENDENCY_MISSINGThe etcd coordinator cannot load etcd3 when the engine first calls it.

Client

CodeWhen
CONNECTION_ERRORThe client fails to connect to the server.
UNAUTHORIZEDThe server refuses the WebSocket upgrade as unauthenticated and closes with 4401.
FORBIDDENThe server refuses the WebSocket upgrade as not permitted and closes with 4403.
TIMEOUTA WebSocket request or a checkpoint exceeds the configured requestTimeout.
TRANSPORT_ERRORThe transport cannot provide the operation, or the caller closes it before the request finishes.
INVALID_RESPONSEThe response is invalid JSON or has another structure than the client expects, as a column answer does when a row is wider or narrower than its columns, or when a value contains an integer outside the 64-bit range of SQLite or a malformed BLOB.
ROUTING_ERRORTopology routing finds no usable primary or read endpoint.
NO_SAFE_PRIMARYTopology routing in coordinator mode finds no current primary for a write or a linearizable read.
INVALID_ARGUMENTA client argument fails validation, such as a read concern on a single call through the topology transport, or a maxRows or maxBytes outside the range from 0 to 2^53-1, which the client refuses before it sends the request.
UNKNOWN_ERRORAn error response includes no recognisable code.

Deciding whether to retry

Retry each of these three groups in a different way, because a retry loop that treats them alike can apply a write twice.

  • Definite rejections are safe to send again. WRITE_OVERLOADED means that Sirannon sheds the write without applying it. The server includes Retry-After in the HTTP response for that code. WRITER_WORKER_UNAVAILABLE and WRITER_WORKER_POST_FAILED report the same about a write that never reaches the writer. EXECUTION_TIMEOUT means that Sirannon rolls back every write of the call, so you can retry the call without applying a write twice, although SQLite can stop the same statement again under the same limit.
  • Indeterminate outcomes need reconciling first. WRITER_WORKER_TIMEOUT and WRITER_WORKER_EXIT leave the outcome unknown, so read the state back before you resend anything that is not idempotent.
  • Routing failures can require fresh cluster metadata. The topology client refreshes its metadata after STALE_PRIMARY, AUTHORITY_LOST, COORDINATOR_UNAVAILABLE, NO_SAFE_PRIMARY, or CONNECTION_ERROR in coordinator mode. It retries a failed read once, while it raises a failed write for reconciliation. Because a connection failure can also mean an outage, check the server's health before you retry.

A validation code such as INVALID_WRITER_WORKER, INVALID_MAX_BODY_BYTES, INVALID_DRIVER, or INVALID_ARGUMENT reports a mistake in the configuration or at the call site. Fix the mistake, because a retry fails in the same way.

UNAUTHORIZED and FORBIDDEN report a refused WebSocket upgrade. Because the server refuses that credential on every try, the client leaves the connection closed. Issue a fresh credential and build a new client to connect again.

HTTP status codes

StatusCodes
400INVALID_REQUEST, INVALID_JSON, EMPTY_BODY, INVALID_READ_LIMIT, INVALID_EXECUTION_TIMEOUT, QUERY_ERROR, TRANSACTION_ERROR, INVALID_DURABILITY, INVALID_SYNCHRONOUS, BATCH_VALIDATION_ERROR, MISSING_ARGUMENT, ARGUMENT_NOT_ALLOWED, UNSUPPORTED_SUBPROTOCOL, DEVICE_CLOCK_AHEAD
401IDENTITY_REQUIRED
403READ_ONLY, FORBIDDEN_SQL, HOOK_DENIED, SQL_NOT_ACCEPTED, BACKUP_RESTORE_NOT_ACCEPTED, DEVICE_SYNC_NOT_ACCEPTED, ENCRYPTION_CHANGE_NOT_ACCEPTED
404DATABASE_NOT_FOUND, NOT_FOUND, UNKNOWN_QUERY
409STALE_PRIMARY, PROTOCOL_VERSION_MISMATCH, MIGRATION_REQUIRED, SCHEMA_AHEAD, BACKUP_CHAIN_BROKEN, BACKUP_RESTORE_IN_PROGRESS, ENCRYPTION_CHANGE_IN_PROGRESS, ENCRYPTION_REQUIRED, REPLICATION_ACTIVE
413PAYLOAD_TOO_LARGE
422EXECUTION_TIMEOUT
500INTERNAL_ERROR, HOOK_ERROR, WRITER_WORKER_TIMEOUT, INVALID_ENCRYPTION_KEY, ENCRYPTION_KEY_MISSING, ENCRYPTION_KEY_REJECTED, DATABASE_NOT_ENCRYPTED, ENCRYPTED_PAGE_CORRUPT, ENCRYPTION_CHANGE_ABORTED
501BULK_LOAD_UNSUPPORTED, SYNC_UNSUPPORTED, BACKUP_UNSUPPORTED, ENCRYPTION_UNSUPPORTED, COLUMN_DETAILS_UNSUPPORTED, EXECUTION_TIMEOUT_UNSUPPORTED
502BACKUP_DESTINATION_ERROR
503DATABASE_CLOSED, SHUTDOWN, READ_CONCERN_ERROR, COORDINATOR_UNAVAILABLE, AUTHORITY_LOST, NO_SAFE_PRIMARY, NODE_NOT_IN_SYNC, NODE_DRAINING, UNSAFE_RECOVERY_REQUIRED, WRITE_OVERLOADED, ENCRYPTION_KEY_UNAVAILABLE

The server answers a code outside the table with 500, while it answers a RequestDeniedError with the status that you give it. The server sends REGISTRY_MISMATCH only over WebSocket, when a live query subscribes, so that code has no HTTP status. The server answers WRITER_WORKER_TIMEOUT with 500, not 503, because the outcome of that write is indeterminate. Configure proxies to preserve that distinction and to make no automatic retries of writes.

WebSocket close codes

The server reports a refusal to an HTTP caller through the status code. A browser WebSocket can't read the status of a refused handshake, so the server reports those refusals to a socket in the close code.

Close codeWhen
1001The server shuts down once it sends the queued replies.
1008The database in the URL is absent or closed.
1009An incoming message exceeds maxBodyBytes. A refusal at the transport level can end the connection without a close frame.
1011The server fails to open the database or to resolve its execution target, in which case it sends an error before it closes.
4290The connection's outbound buffer exceeds maxWebSocketBackpressureBytes, or the client sends more than 256 messages, or more than four times maxBodyBytes, while the server opens the database. Clients that use device sync or subscription resumption recover from it.
4401The authenticate hook refuses the upgrade with status 401, with a close reason that contains your code and message.
4403The hook refuses the upgrade with status 403.
4410The server removes the cursor of a connected device. Reconnect so that the resumption check can report whether the device needs a snapshot.

The client reconnects after 4290 and resumes each subscription from its cursor. It treats 4401, 4403, and any code from 4000 to 4099 as a refusal and leaves that connection closed, because the server refuses that credential every time.