Brain Docs

Reference

TypeScript SDKInstallationHTTP clientWire client
ErrorsRetriesPagination
Brain/Docs
✦ ASKBrain on GitHubDashboard
TypeScript SDKErrors

Errors

Both error taxonomies — the wire BrainError hierarchy with its nine categories and the eighty-odd codes, and the HTTP tier's BrainHttpError.

PURPOSE

The two tiers fail differently and the SDK does not paper over it. The wire client throws a BrainError hierarchy carrying the protocol's own error frames; the HTTP client throws BrainHttpError carrying a status and a string code. This page catalogs both, the four classifying predicates, and the code families worth branching on.

Wire tier: the BrainError hierarchy

ParameterTypeRequired
BrainErrorclassrequired

Base class for every wire-client failure. Catch this to catch everything.

ProtocolErrorextends BrainErroroptional

The peer broke the protocol sequence — an unexpected opcode, a response on an unknown stream. Not retryable; the connection's state is no longer trustworthy.

TransportErrorextends BrainErroroptional

The socket failed. Retryable.

ConnectionClosedextends BrainErroroptional

The peer closed the connection. Retryable — on a new connection.

BrainTimeoutextends BrainErroroptional

An operation missed its deadline. Carries timeoutMs. Retryable.

VersionMismatchextends BrainErroroptional

The server chose a wire version the client did not offer. Carries chosen and supported. Never retryable — upgrade one side.

ServerErrorextends BrainErroroptional

The server returned a structured ERROR frame. Carries code, category, retryAfterMs and the full response.

A corrupt frame throws FrameError from the wire layer. It is fatal for the connection, not for the request.

Categories

ServerError.category is an ErrorCategoryWire, and it is the coarse branch:

CategoryValueMeaningRetry
Protocol0Malformed or out-of-sequence request.No
Authentication1The credential was rejected.No
Authorization2The identity lacks permission — including act_as denial.No
Validation3The request failed input validation.No
NotFound4The referenced thing does not exist.No
Conflict5Idempotency or transaction conflict.No
ResourceExhausted6Rate or quota limit. May carry retryAfterMs.Yes
Internal7Server-side failure.No
Unavailable8The shard is temporarily unavailable.Yes

Codes

ServerError.code is the precise verdict — a u16 the SDK surfaces as WireErrorCode. The families, by prefix:

OptionTypeDefault / Env
0x0001–0x000BFraming

BadMagic, BadHeaderCrc, BadPayloadCrc, BadOpcode, BadVersion, BadFrame, OversizePayload, ReservedFieldNonZero, BadFlagCombination, MalformedPayload, MalformedVector.

0x0020–0x0025Authentication

VersionNotSupported, NoSuchAuthMethod, Unauthenticated, NotAuthenticated, AuthBackendUnavailable, SessionExpired.

0x0030–0x0033Authorization

PermissionDenied, AdminPermissionRequired, WrongShard, ActAsDenied — the principal lacks the canActAs grant, or targeted a namespace outside its allowlist.

0x0040–0x004CValidation

InvalidArgument, MissingRequiredField, TextTooLarge, TextEmpty, BadSessionId, BadMemoryKind, BadEdgeKind, BadStrategyHint, TopKOutOfRange, BudgetTooLarge, BadModelFingerprint, PredicateNotInSchema, RelationTypeNotInSchema.

0x0050–0x0054Not found

MemoryNotFound, ContextNotFound, SubscriptionNotFound, SnapshotNotFound, TxnNotFound.

0x0060–0x0066Conflict

IdempotencyConflict, TransactionConflict, TransactionTimeout, StreamIdInUse, SubscriptionLsnTooOld, CardinalityViolation, LlmCredentialMissing (0x0066).

0x0070–0x0077Resource exhausted

OutOfSlots, OutOfDisk, OutOfMemory, RateLimited, StreamLimitExceeded, ConnectionLimitExceeded, TransactionLimitExceeded, TransactionTooLarge.

0x0080–0x0085Internal

Internal, StorageError, IndexError, EmbeddingError, MetadataError, Cancelled.

0x0090–0x0095Unavailable

ShardUnavailable, Overloaded, Restarting, Maintenance, RetrieverDegraded, LlmCredentialUnavailable (0x0095).

0x0120–0x0172Graph and extraction

SchemaInvalid, SchemaMigrationRequired, EntityNotFound, EntityTypeMismatch, EntityAmbiguous, EntityMergeConflict, StatementNotFound, StatementObjectTypeMismatch, StatementContradictsExisting, QueryTimeout, QueryOverBudget, ExtractorDisabled, ExtractorBudgetExceeded, ExtractionFailed.

An unrecognised code decodes to Unknown rather than throwing, so a client built against an older SDK still surfaces a newer server's errors.

Classifying

Four predicates, all exported from the package root:

ParameterTypeRequired
isRetryable(err)booleanrequired

true for ConnectionClosed, BrainTimeout, TransportError, and a ServerError whose category is ResourceExhausted or Unavailable. Nothing else. This is the signal the retry combinator consults.

isActAsDenied(err)booleanoptional

ServerError with code ActAsDenied. Never retryable; the fix is a differently-scoped credential.

isLlmCredentialMissing(err)booleanoptional

ServerError with code LlmCredentialMissing (0x0066, category Conflict, HTTP 409 on the edge): no provider credential is registered. Terminal — isRetryable is false and retrying cannot create a key, so surface it as "register a provider key". See Provider credentials.

isLlmCredentialUnavailable(err)booleanoptional

ServerError with code LlmCredentialUnavailable (0x0095, category Unavailable, HTTP 503 on the edge): a credential exists, but the broker was unreachable, timed out or failed transiently. Retryable. The two are deliberately separate conditions — collapsing them would either spin forever against a tenant that has no key, or permanently fail a write for a tenant whose key is fine.

import {
  ServerError,
  ErrorCategoryWire,
  isRetryable,
  isLlmCredentialMissing,
} from "@brain-db/sdk";

try {
  await client.encode(req);
} catch (e) {
  if (isLlmCredentialMissing(e)) return promptForProviderKey();
  if (isRetryable(e)) return scheduleRetry();
  if (e instanceof ServerError && e.category === ErrorCategoryWire.Validation) {
    console.error("bad request:", e.response.message);
  }
  throw e;
}

HTTP tier: BrainHttpError

One class, not a hierarchy.

FieldTypePresence
statusnumberalways

The HTTP status. 0 means the request never got an answer — a transport failure or a client-side timeout — and is the value the retry policy treats as retryable alongside 503 and 429.

codestringalways

The edge's stable string code: unauthorized, llm_credential.missing, llm_credential.unavailable, and so on. Branch on this, not on the message.

fieldErrorsReadonlyArray<…>always

Per-field validation detail, each { field, code?, message }. Empty unless the edge rejected specific fields.

messagestringalways

Human-readable. Never parse it.

The constructor also uses status: 0 with code: "config" for client-side misconfiguration — a missing or empty apiKey, an apiKey carrying an ASCII control character, a baseUrl that is not http/https — thrown before any request is attempted. Every other status: 0 is a transport failure or a timeout, so test code before treating a 0 as transient.

import { BrainHttpError } from "@brain-db/sdk";

try {
  await brain.createStatement(input);
} catch (e) {
  if (e instanceof BrainHttpError) {
    if (e.code === "config") throw e;               // a bug in the call, not a blip
    if (e.status === 0) return retryLater();        // never reached the edge
    if (e.code === "llm_credential.missing") return promptForProviderKey();
    if (e.code === "llm_credential.unavailable") return retryLater();
    for (const f of e.fieldErrors) console.error(`${f.field}: ${f.message}`);
  }
  throw e;
}
Validation failures are not always exceptions

validateSchema, uploadSchema, replaceSchema and dropSchema all resolve with a populated validationErrors array rather than throwing. A try/catch around them catches transport and auth failures only. See Schema.

See also
RetriesProvider credentialsWire client

Was this page helpful?

ping

A connection-level liveness check that works while streams are in flight.

Retries

Both retry layers — the HTTP client's built-in policy with its idempotent-only verb list, and the wire tier's backoff primitives.

On this page

Wire tier: the BrainError hierarchyCategoriesCodesClassifyingHTTP tier: BrainHttpError
Suggest an editOpen in Playground