Brain Docs
Build

Wire it in

Drop it into an existing loopA chatbot that remembersHandling corrections

Production

Alongside your RAGOne space per customerErasing a subject

Working with the API

Error handlingRetries and cancellationIdempotencyStreamingGraph queriesFaithfulness checkingIdentity walkthroughNamespace lifecycle

Reference

Brain/Docs
✦ ASKBrain on GitHubDashboard
BuildError handling

Error handling

Catch the BrainError hierarchy from the wire client, decide retry vs surface, and know which of the nine error categories are transient.

PURPOSE

Handle Brain failures correctly: catch the right error type for the client you're using, decide whether a failure is worth retrying, and surface caller-fault errors instead of retrying them into the ground.

◇Prerequisites
  • A Brain client (BrainClient).
  • Familiarity with the nine wire error categories (see SDK errors).
▸What you'll build

A wrapper around Brain calls that classifies a failure as retry / surface / alert using the SDK's own taxonomy, without hard-coding a status list.

One taxonomy

BrainClient throws a BrainError hierarchy — ProtocolError, ConnectionClosed, BrainTimeout, VersionMismatch, and ServerError (plus the ActAsDenied case). This guide is the task recipe; the exhaustive class lists and code tables live in the reference pages, so branch on the SDK's own helpers rather than re-implementing them.

Full references: TypeScript errors, Python errors.

Handling wire errors

The wire client separates failure layers so you can react to each differently. Catch BrainError at the boundary; catch a subclass only where you have a specific recovery.

import { ServerError, ErrorCategoryWire, isActAsDenied, BrainError } from "@brain-db/sdk";

try {
  await client.encode(req);
} catch (e) {
  if (isActAsDenied(e)) throw e;                 // wrong-scoped credential — fix it
  if (e instanceof ServerError && e.category === ErrorCategoryWire.Validation) {
    throw e;                                      // bad input — surface to caller
  }
  if (e instanceof BrainError) {
    // ProtocolError / ConnectionClosed / BrainTimeout / ServerError — see below
  }
  throw e;
}
from brain_db_sdk import ServerError, ActAsDenied, BrainTimeout, BrainError

try:
    client.encode(req)
except ActAsDenied:
    raise                     # lacks can_act_as / namespace outside allowlist
except ServerError as e:
    print(f"{e.code:#06x}", e.category, e.retry_after_ms)
    raise
except BrainTimeout:
    ...                       # bump request_timeout, or retry
except BrainError:
    raise
use brain_db_sdk::BrainError;
use brain_db_sdk::wire::types::ErrorCategoryWire;

if let Err(e) = client.encode(&req).await {
    match &e {
        // Authorization covers act_as denied — a wrong-scoped credential; fix it.
        BrainError::Server { category: ErrorCategoryWire::Authorization, .. } => return Err(e.into()),
        // bad input — surface to caller
        BrainError::Server { category: ErrorCategoryWire::Validation, .. } => return Err(e.into()),
        // Protocol / Closed / Timeout / other Server verdicts — see below
        _ => {}
    }
    return Err(e.into());
}

ServerError.category is one of the nine wire categories. Only two are transient — ResourceExhausted and Unavailable (which may carry retryAfterMs). The other seven (Protocol, Authentication, Authorization, Validation, NotFound, Conflict, Internal) will not succeed on a blind retry.

Let the SDK classify retryability

Don't hard-code a status list — use the SDK's own predicate so a category you didn't enumerate still classifies correctly.

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

try {
  return await client.recall(req);
} catch (e) {
  if (isRetryable(e)) return retryWithBackoff(() => client.recall(req));
  throw e;
}
from brain_db_sdk import is_retryable, with_retry

try:
    return client.recall(req)
except Exception as e:
    if is_retryable(e):
        return with_retry(lambda: client.recall(req))
    raise
use brain_db_sdk::{with_retry, RetryPolicy};

match client.recall(&req).await {
    Ok(answer) => Ok(answer),
    Err(e) if e.is_retryable() => with_retry(&RetryPolicy::default(), || client.recall(&req)).await,
    Err(e) => Err(e),
}

isRetryable / is_retryable returns true for a connection drop, a timeout, or a ResourceExhausted / Unavailable verdict — and false for validation and auth failures. See Retries and cancellation.

Page on Internal / engine.error and persistent Unavailable; log auth and validation failures at WARN — those are your inputs and credentials, not an incident. Never retry a Conflict: a same-id-different-params write will keep conflicting until you fix the request.

Over the HTTP edge

If you call the REST API (BrainHttpClient or raw HTTP) instead of the wire client, the same nine wire categories collapse onto one JSON error envelope and a small set of HTTP codes:

{ "error": { "code": "not_found", "message": "memory 42 not found" } }

Branch on code, never parse message. The codes are bad_request (400), unauthorized (401), forbidden (403), not_found (404), conflict (409), engine.unavailable (503, retriable), and engine.error (502); the middleware can also return 408 Request Timeout and 413 Payload Too Large. The retriable one is engine.unavailable — it maps from the same ResourceExhausted / Unavailable verdicts, so back off and retry it and surface the rest. Full mapping table: API → Errors.

The three error surfaces, kept apart

OptionTypeDefault / Env
Wire BrainErrorthe binary protocol

A class hierarchy in TypeScript and Python, an enum in Rust. Carries the protocol's own code and category, so you can branch on the exact verdict. See Errors in the SDK.

HTTP BrainHttpErrorthe JSON edge

One type carrying status, a stable string code and field_errors. status === 0 means the request never reached the edge — a transport failure or client timeout — and is what the retry policy keys on alongside 429 and 503.

Not an error at allthe schema verbs

validateSchema and its siblings resolve with a populated validation_errors array. A try/catch around them catches transport and auth failures only, so code that checks nothing else treats an invalid schema as an accepted one.

Conditions worth a named branch

ConditionHow to detect itWhat to do
No provider credentialllm_credential.missing / 409; isLlmCredentialMissingPrompt an operator to register one. Never retry — it cannot self-heal
Provider briefly unusablellm_credential.unavailable / 503Retry with backoff
act_as refusedActAsDenied (0x0033); isActAsDeniedA differently-scoped credential, not a retry
Ambiguous entity resolutionoutcome === "Ambiguous" on a successful callDecide from candidate_ids. Ignoring it writes no link and logs nothing
Truncated traversaltruncated: true on a successful callRaise the budget, or say the view is partial

The last two are the ones that bite: they arrive as successes, so nothing in a catch block will ever see them.

See also
Retries and cancellationRetry policy, backoff, and timeouts.IdempotencyWhy a Conflict means same id, different params.SDK errors (Python)The same hierarchy in the Python client.SDK errorsThe complete client error hierarchy.

Was this page helpful?

Erasing a subject

Deleting everything about a person — soft versus hard forget, why the cascade matters, and which parts of a data-subject request are yours to own.

Retries and cancellation

Retry wire calls safely with the request-id contract and bound calls with timeouts — the SDK takes no external AbortSignal.

On this page

One taxonomyHandling wire errorsLet the SDK classify retryabilityOver the HTTP edgeThe three error surfaces, kept apartConditions worth a named branch
Suggest an editOpen in Playground