> ## Documentation Index
> Fetch the complete documentation index at: https://docs.maximem.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Maximem Synap is a managed memory layer for AI agents: it ingests conversations and documents, extracts structured memory, and returns scoped context to the agent at retrieval time.
> The Python and JavaScript/TypeScript SDKs are the supported way to use Synap. Write integration code with SDK calls, not raw HTTP requests.
> Start with the Quickstart: https://docs.maximem.ai/getting-started/quickstart.md. Every SDK method is documented in the SDK reference: https://docs.maximem.ai/sdk-reference/overview.md.
> For requests about adding Vity memory to OpenClaw, Hermes, an MCP client, or a browser, start with the Vity Quickstart: https://docs.maximem.ai/vity/quickstart.md.

# Error Handling

> Handle errors gracefully in your Synap integration.

## Overview

The Synap SDK uses a structured error hierarchy to distinguish between transient errors (which are automatically retried) and permanent errors (which require your intervention). Understanding this hierarchy is essential for building robust integrations. This page is the handling guide: the hierarchy, when each error fires, and the try/except patterns to catch them.

> [card] [Full error reference →](https://docs.maximem.ai/sdk-reference/errors.md)
>
> For the exhaustive catalog of server-side error codes (the wire-level `code` field, HTTP status, and `details` shape) see [Error Codes](https://docs.maximem.ai/sdk-reference/errors.md). For the complete SDK exception table at a glance, see [SDK Reference: Error handling](https://docs.maximem.ai/sdk-reference/overview.md#error-handling).

## Error Hierarchy

All Synap errors inherit from `SynapError`. The two main branches determine retry behavior:

```
SynapError (base)
├── SynapTransientError (retryable: SDK auto-retries)
│   ├── NetworkTimeoutError
│   ├── RateLimitError
│   ├── ServiceUnavailableError
│   └── AgentUnavailableError
└── SynapPermanentError (non-retryable: requires code/config fix)
    ├── InvalidInputError
    │   ├── InvalidInstanceIdError
    │   └── InvalidConversationIdError
    ├── AuthenticationError
    ├── ContextNotFoundError
    ├── SessionExpiredError
    ├── InsufficientCreditsError
    ├── ListeningAlreadyActiveError
    └── ListeningNotActiveError
```

All errors include an optional `correlation_id` field that uniquely identifies the request. This ID is invaluable for debugging and when contacting Synap support.

> [!NOTE]
>
> The hierarchy below reflects the full public error surface. `AgentUnavailableError` is transient (retryable); all others under `SynapPermanentError` are non-retryable.

## Transient Errors

Transient errors represent temporary conditions that typically resolve on their own. The SDK **automatically retries** these errors according to your configured [retry policy](#retry-policy-configuration). You only need to handle them if all retry attempts are exhausted.

### NetworkTimeoutError

**NetworkTimeoutError** `SynapTransientError`

Raised when a network request to Synap Cloud times out before completing.

**When it occurs:**

* Network connectivity issues between your application and Synap Cloud
* DNS resolution failures
* The request exceeded the configured `connect` or `read` timeout

**How to handle:**

> [!NOTE]
>
> `conversation_id` must be a valid UUID string; non-UUID values are rejected by the server. Generate one with `str(uuid.uuid4())`, or reuse the UUID you already manage per conversation. The examples below use `str(uuid.uuid4())` to make this explicit.

```python Python theme={null}
import uuid
from maximem_synap import NetworkTimeoutError

try:
    context = await sdk.conversation.context.fetch(
        conversation_id=str(uuid.uuid4()),
        mode="fast"
    )
except NetworkTimeoutError as e:
    logger.warning(
        "Network timeout after all retries (correlation_id=%s)",
        e.correlation_id
    )
    # Fall back to cached context or proceed without memory
    context = None
```

```javascript JavaScript theme={null}
import { randomUUID } from 'node:crypto';
import { NetworkTimeoutError, isSynapError } from '@maximem/synap-js-sdk';

try {
  let context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
    mode: 'fast',
  });
} catch (e) {
  if (!(e instanceof NetworkTimeoutError)) throw e;
  console.warn('Network timeout after all retries (correlation_id=%s)', e.correlationId);
    // Fall back to cached context or proceed without memory
  context = null;
}
```

```typescript TypeScript theme={null}
import { randomUUID } from 'node:crypto';
import { NetworkTimeoutError, isSynapError } from '@maximem/synap-js-sdk';

try {
  let context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
    mode: 'fast',
  });
} catch (e) {
  if (!(e instanceof NetworkTimeoutError)) throw e;
  console.warn('Network timeout after all retries (correlation_id=%s)', e.correlationId);
    // Fall back to cached context or proceed without memory
  context = null;
}
```

### RateLimitError

**RateLimitError** `SynapTransientError`

Raised when your application exceeds the rate limit for the Synap API. Includes a `retry_after_seconds` field indicating how long to wait before retrying, and a `reason` naming the stop when it was credits rather than traffic.

**When it occurs:**

* Too many requests in a short time window
* Burst traffic exceeding your plan's rate limit
* On the **Trial** plan, the monthly credit cap has been reached. Retrying does not help here: requests stop until the next monthly cycle or an upgrade. A paid plan whose renewal payment is past due is treated the same way until the payment goes through.

**Telling a credit stop from a traffic limit:** read `reason` (`e.reason`), rather than inferring it from a balance lookup.

| `reason` | What happened | What clears it |
| - | - | - |
| `trial_limit_reached` | The Trial cap is spent. `upgrade_url` points at the upgrade page. | An upgrade, or the next cycle. |
| `subscription_inactive` | A paid plan whose subscription is past due, unpaid or cancelled. `manage_url` points at Plan and billing. | The payment going through. |
| `None` (`null` in JS) | An ordinary traffic limit. | Waiting `retry_after_seconds`. |

See [Pricing & Credits](https://docs.maximem.ai/resources/pricing.md#overage--hard-caps).

**How to handle:**

```python Python theme={null}
from maximem_synap import RateLimitError

try:
    response = await sdk.memories.create(
        document=doc,
        document_type="ai-chat-conversation",
        user_id=uid,
        customer_id=cid,
    )
except RateLimitError as e:
    logger.warning(
        "Rate limited (reason=%s). Retry after %s seconds (correlation_id=%s)",
        e.reason, e.retry_after_seconds, e.correlation_id
    )
    if e.reason == "trial_limit_reached":
        # Not traffic: the Trial credits are spent. Upgrade at e.upgrade_url.
        ...
    elif e.reason == "subscription_inactive":
        # The subscription lapsed. Fix the payment at e.manage_url.
        ...
    # The SDK retries automatically, but if all retries are exhausted:
    # - Queue the operation for later
    # - Reduce request frequency
    # - Consider upgrading your plan
```

```javascript JavaScript theme={null}
import { RateLimitError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: doc,
    document_type: 'ai-chat-conversation',
    user_id: uid,
    customer_id: cid,
  });
} catch (e) {
  if (!(e instanceof RateLimitError)) throw e;
  console.warn('Rate limited (reason=%s). Retry after %s seconds (correlation_id=%s)', e.reason, e.retryAfterSeconds, e.correlationId);
  // Not traffic: 'trial_limit_reached' means the Trial credits are spent
  // (upgrade at e.upgradeUrl), 'subscription_inactive' means the subscription
  // lapsed (fix the payment at e.manageUrl).
    // The SDK retries automatically, but if all retries are exhausted:
    // - Queue the operation for later
    // - Reduce request frequency
    // - Consider upgrading your plan
}
```

```typescript TypeScript theme={null}
import { RateLimitError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: doc,
    document_type: 'ai-chat-conversation',
    user_id: uid,
    customer_id: cid,
  });
} catch (e) {
  if (!(e instanceof RateLimitError)) throw e;
  console.warn('Rate limited (reason=%s). Retry after %s seconds (correlation_id=%s)', e.reason, e.retryAfterSeconds, e.correlationId);
  // Not traffic: 'trial_limit_reached' means the Trial credits are spent
  // (upgrade at e.upgradeUrl), 'subscription_inactive' means the subscription
  // lapsed (fix the payment at e.manageUrl).
    // The SDK retries automatically, but if all retries are exhausted:
    // - Queue the operation for later
    // - Reduce request frequency
    // - Consider upgrading your plan
}
```

> [!NOTE]
>
> The SDK's built-in retry policy respects `retry_after_seconds` automatically. If the rate limit is short (a few seconds), the SDK waits and retries without raising the error to your code. The error only surfaces when all retry attempts are exhausted.

### ServiceUnavailableError

**ServiceUnavailableError** `SynapTransientError`

Raised when Synap Cloud is temporarily unavailable due to maintenance, deployment, or an outage.

**When it occurs:**

* Synap Cloud is undergoing maintenance
* A rolling deployment is in progress
* Temporary backend issues

**How to handle:**

```python Python theme={null}
import uuid
from maximem_synap import ServiceUnavailableError

try:
    context = await sdk.conversation.context.fetch(
        conversation_id=str(uuid.uuid4()),
        mode="fast"
    )
except ServiceUnavailableError as e:
    logger.error(
        "Synap Cloud unavailable (correlation_id=%s)",
        e.correlation_id
    )
    # Serve from cache if available, or degrade gracefully
```

```javascript JavaScript theme={null}
import { randomUUID } from 'node:crypto';
import { ServiceUnavailableError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
    mode: 'fast',
  });
} catch (e) {
  if (!(e instanceof ServiceUnavailableError)) throw e;
  console.error('Synap Cloud unavailable (correlation_id=%s)', e.correlationId);
    // Serve from cache if available, or degrade gracefully
}
```

```typescript TypeScript theme={null}
import { randomUUID } from 'node:crypto';
import { ServiceUnavailableError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
    mode: 'fast',
  });
} catch (e) {
  if (!(e instanceof ServiceUnavailableError)) throw e;
  console.error('Synap Cloud unavailable (correlation_id=%s)', e.correlationId);
    // Serve from cache if available, or degrade gracefully
}
```

## Instance build errors

New instances need a memory architecture build before they can handle runtime reads or writes. While that build runs, the server returns HTTP 409 `instance_not_ready`. The SDK does not retry it inside the call.

| Error | Meaning | What to do |
| - | - | - |
| `InstanceNotReadyError` | The instance is still building. It extends `ConflictError`. | Wait for `retry_after_seconds` (at most 300 seconds), then retry later. A read can proceed without memory; queue a write. |
| `InstanceBuildFailedError` | The build exhausted its attempts. It extends `ConflictError`. | Do not retry the runtime call. Rebuild the instance and wait for it to be ready. |

`InstanceNotReadyError` includes `retry_after_seconds`, `instance_id`, `state`, and `from_cooldown`. `InstanceBuildFailedError` includes `instance_id`, `attempts`, and `hint`. Use `maximem-synap instances wait <instance-id>` to follow a build; builds normally take 15 to 20 minutes.

> [!NOTE]
>
> The event stream retains up to 5,000 events. Do not treat it as an unbounded replay log.

## Permanent Errors

Permanent errors indicate problems that will not resolve by retrying. They require changes to your code, configuration, or data.

### InvalidInputError

**InvalidInputError** `SynapPermanentError`

Raised when the request contains invalid parameters or data that fails validation.

**When it occurs:**

* Invalid `document_type` value
* Missing required fields
* Parameter values outside valid ranges
* Malformed data in the request body

**How to handle:**

```python Python theme={null}
from maximem_synap import InvalidInputError

try:
    response = await sdk.memories.create(
        document="",                       # Empty document
        document_type="invalid-type",      # Invalid document_type value
        user_id="user_123",
        customer_id="acme_corp",
    )
except InvalidInputError as e:
    logger.error("Invalid input: %s", e)
    # Fix the input data and retry
```

```javascript JavaScript theme={null}
import { InvalidInputError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: '',  // Empty document
    document_type: 'invalid-type',
    // Invalid document_type value
    user_id: 'user_123',
    customer_id: 'acme_corp',
  });
} catch (e) {
  if (!(e instanceof InvalidInputError)) throw e;
  console.error('Invalid input: %s', e);
    // Fix the input data and retry
}
```

```typescript TypeScript theme={null}
import { InvalidInputError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: '',  // Empty document
    document_type: 'invalid-type',
    // Invalid document_type value
    user_id: 'user_123',
    customer_id: 'acme_corp',
  });
} catch (e) {
  if (!(e instanceof InvalidInputError)) throw e;
  console.error('Invalid input: %s', e);
    // Fix the input data and retry
}
```

### InvalidInstanceIdError

**InvalidInstanceIdError** `InvalidInputError`

A defined subtype of `InvalidInputError` for an unknown or malformed `instance_id`.

> [!NOTE]
>
> A **malformed** `instance_id` is rejected by the SDK itself, and raised from the constructor before any request is made: you do not reach `initialize()`. An id that is well-formed but **unknown** to the server is a different case: it comes back as an HTTP 400 and surfaces as the base `InvalidInputError`. Catching `InvalidInputError` handles both, since this is a subtype of it.

**When it occurs:**

* The `instance_id` does not match the expected format: `inst_` followed by 16 hex characters, e.g. `inst_a1b2c3d4e5f67890`. Raised by `MaximemSynapSDK(...)` itself; an empty value is left alone, since the instance is normally resolved from the API key during `initialize()`.
* The instance has been deleted or deactivated (server-side, surfaces as `InvalidInputError`)
* A typo in the instance ID

**How to handle:**

```python Python theme={null}
from maximem_synap import InvalidInputError

try:
    sdk = MaximemSynapSDK(instance_id=configured_id, api_key=key)
    await sdk.initialize()
except InvalidInputError as e:   # also catches InvalidInstanceIdError
    logger.error(
        "Invalid instance ID. Verify in the Synap Dashboard. "
        "(correlation_id=%s)", getattr(e, "correlation_id", None)
    )
    raise
```

```javascript JavaScript theme={null}
import { SynapClient, InvalidInputError } from '@maximem/synap-js-sdk';

try {
  const sdk = new SynapClient({ instanceId: configuredId, apiKey: key });
  await sdk.initialize();
} catch (e) {
  // Also catches InvalidInstanceIdError, which extends InvalidInputError.
  if (!(e instanceof InvalidInputError)) throw e;
  console.error(
    'Invalid instance ID. Verify in the Synap Dashboard. (correlation_id=%s)',
    e.correlationId,
  );
  throw e;
}
```

```typescript TypeScript theme={null}
import { SynapClient, InvalidInputError } from '@maximem/synap-js-sdk';

try {
  const sdk = new SynapClient({ instanceId: configuredId, apiKey: key });
  await sdk.initialize();
} catch (e) {
  // Also catches InvalidInstanceIdError, which extends InvalidInputError.
  if (!(e instanceof InvalidInputError)) throw e;
  console.error(
    'Invalid instance ID. Verify in the Synap Dashboard. (correlation_id=%s)',
    e.correlationId,
  );
  throw e;
}
```

> [!TIP]
>
> Passing `instance_id` is optional, and usually unnecessary: the API key already identifies its instance and the SDK resolves it during `initialize()`. Omitting it avoids this error class entirely.

### InvalidConversationIdError

**InvalidConversationIdError** `InvalidInputError`

A defined subtype of `InvalidInputError` for a malformed `conversation_id` (for example, a non-UUID string).

> [!NOTE]
>
> The SDK currently surfaces a malformed `conversation_id` as the base **`InvalidInputError`** (HTTP 400), not as this specific subtype. Catch `InvalidInputError`. Note that a *well-formed* `conversation_id` with no messages yet does **not** raise; it returns an empty `ContextResponse` (see [cold-start behavior](#contextnotfounderror)).

**When it occurs:**

* The `conversation_id` is not a valid UUID
* A typo or wrong identifier format

**How to handle:**

```python Python theme={null}
import uuid
from maximem_synap import InvalidInputError

try:
    context = await sdk.conversation.context.fetch(
        conversation_id=str(uuid.uuid4())  # must be a valid UUID
    )
except InvalidInputError as e:
    logger.warning("Malformed conversation_id: %s", e)
    # Generate a valid UUID and retry
```

```javascript JavaScript theme={null}
import { randomUUID } from 'node:crypto';
import { InvalidInputError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),  // must be a valid UUID
  });
} catch (e) {
  if (!(e instanceof InvalidInputError)) throw e;
  console.warn('Malformed conversation_id: %s', e);
    // Generate a valid UUID and retry
}
```

```typescript TypeScript theme={null}
import { randomUUID } from 'node:crypto';
import { InvalidInputError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),  // must be a valid UUID
  });
} catch (e) {
  if (!(e instanceof InvalidInputError)) throw e;
  console.warn('Malformed conversation_id: %s', e);
    // Generate a valid UUID and retry
}
```

### AuthenticationError

**AuthenticationError** `SynapPermanentError`

Raised when the SDK cannot authenticate with Synap Cloud. This is a general authentication failure.

**When it occurs:**

* API key is invalid or revoked
* No API key was provided (neither `SYNAP_API_KEY` env var nor the `api_key=` constructor argument)
* The instance's credentials have been rotated without updating the API key your application uses

**How to handle:**

```python Python theme={null}
from maximem_synap import AuthenticationError

try:
    await sdk.initialize()
except AuthenticationError as e:
    logger.error(
        "Authentication failed: %s (correlation_id=%s)",
        e, e.correlation_id
    )
    # Re-bootstrap with a new token, or check SYNAP_API_KEY in the environment
```

```javascript JavaScript theme={null}
import { AuthenticationError, isSynapError } from '@maximem/synap-js-sdk';

try {
  await sdk.initialize();
} catch (e) {
  if (!(e instanceof AuthenticationError)) throw e;
  console.error('Authentication failed: %s (correlation_id=%s)', e, e.correlationId);
    // Re-bootstrap with a new token, or check SYNAP_API_KEY in the environment
}
```

```typescript TypeScript theme={null}
import { AuthenticationError, isSynapError } from '@maximem/synap-js-sdk';

try {
  await sdk.initialize();
} catch (e) {
  if (!(e instanceof AuthenticationError)) throw e;
  console.error('Authentication failed: %s (correlation_id=%s)', e, e.correlationId);
    // Re-bootstrap with a new token, or check SYNAP_API_KEY in the environment
}
```

### ContextNotFoundError

**ContextNotFoundError** `SynapPermanentError`

Raised when a requested context resource genuinely cannot be located, distinct from a valid resource that simply has no memories yet, which returns an **empty** `ContextResponse` rather than raising.

**Empty result vs. raised error, which happens per method:**

* `sdk.conversation.context.fetch()`: a brand-new or never-ingested `conversation_id` returns an **empty** `ContextResponse` (`facts == []`, `preferences == []`, etc.), **not** an error. This is the normal cold-start path. A malformed (non-UUID) `conversation_id` raises `InvalidInputError` instead.
* `sdk.user.context.fetch()` / `sdk.customer.context.fetch()` / `sdk.client.context.fetch()`: a scope that has never had memories ingested also returns an **empty** `ContextResponse`. Treat empty lists as "no context yet," not as an error.

`ContextNotFoundError` is reserved for the case where the underlying context resource itself is missing or was removed, not for the everyday "new conversation / new user" case.

**When it occurs:**

* A previously available context resource was deleted before retrieval
* The backend cannot locate the addressed context resource (as opposed to locating it and finding it empty)

**How to handle:**

```python Python theme={null}
from maximem_synap import ContextNotFoundError

try:
    context = await sdk.user.context.fetch(user_id="user_12345")
except ContextNotFoundError:
    logger.info("Context resource missing for user, starting with empty state")
    context = None

# Note: a user who simply has no memories yet does NOT raise here; the fetch
# returns an empty ContextResponse. Check `not context.facts and not
# context.preferences and ...` for the cold-start case rather than relying on
# this exception.
```

```javascript JavaScript theme={null}
import { ContextNotFoundError } from '@maximem/synap-js-sdk';

let context = null;
try {
  context = await sdk.user.context.fetch({ user_id: 'user_12345' });
} catch (e) {
  if (!(e instanceof ContextNotFoundError)) throw e;
  console.info('Context resource missing for user, starting with empty state');
  context = null;
}

// Note: a user who simply has no memories yet does NOT raise here; the fetch
// returns an empty response, and each collection may be absent entirely.
// Check `!(context?.facts?.length) && !(context?.preferences?.length)` for the
// cold-start case rather than relying on this exception.
```

```typescript TypeScript theme={null}
import { ContextNotFoundError, type RawContext } from '@maximem/synap-js-sdk';

let context: RawContext | null = null;
try {
  context = await sdk.user.context.fetch({ user_id: 'user_12345' });
} catch (e) {
  if (!(e instanceof ContextNotFoundError)) throw e;
  console.info('Context resource missing for user, starting with empty state');
  context = null;
}

// Note: a user who simply has no memories yet does NOT raise here; the fetch
// returns an empty response, and each collection may be absent entirely.
// Check `!(context?.facts?.length) && !(context?.preferences?.length)` for the
// cold-start case rather than relying on this exception.
```

### SessionExpiredError

**SessionExpiredError** `SynapPermanentError`

Raised when the current session has expired and cannot be resumed. Sessions are time-bounded and must be re-established after expiry.

**When it occurs:**

* The session has been idle beyond its expiry window
* The session was invalidated server-side (e.g., credential rotation)

**How to handle:**

```python Python theme={null}
import uuid
from maximem_synap import SessionExpiredError

try:
    context = await sdk.conversation.context.fetch(
        conversation_id=str(uuid.uuid4())
    )
except SessionExpiredError as e:
    logger.warning(
        "Session expired (correlation_id=%s). Re-initializing...",
        e.correlation_id
    )
    await sdk.initialize()
    # Retry the operation
```

```javascript JavaScript theme={null}
import { randomUUID } from 'node:crypto';
import { SessionExpiredError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
  });
} catch (e) {
  if (!(e instanceof SessionExpiredError)) throw e;
  console.warn('Session expired (correlation_id=%s). Re-initializing...', e.correlationId);
  await sdk.initialize();
    // Retry the operation
}
```

```typescript TypeScript theme={null}
import { randomUUID } from 'node:crypto';
import { SessionExpiredError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
  });
} catch (e) {
  if (!(e instanceof SessionExpiredError)) throw e;
  console.warn('Session expired (correlation_id=%s). Re-initializing...', e.correlationId);
  await sdk.initialize();
    // Retry the operation
}
```

### InsufficientCreditsError

**InsufficientCreditsError** `SynapPermanentError`

Raised when the client's credit balance is too low to satisfy the request. Carries `balance_credits`, `minimum_required_credits`, `recovery_url`, `redeem_url`, plus `reason` and `manage_url`, so you can surface the right next-step to the user. See [Pricing & Credits](https://docs.maximem.ai/resources/pricing.md#overage--hard-caps) for how credits and overage work.

**When it occurs:**

* A **paid plan** (Starter, Pro or Scale) has used up its credits and **overages are off** for the account. Overages are off by default, so this is what a paid account sees at zero until its owner turns them on.
* The current credit balance is below the minimum required for the requested operation, and overages are off.

With overages on, requests keep working past zero and this error is not raised for running out; the extra usage is billed instead. On the Trial plan, running out is reported as [`RateLimitError`](#ratelimiterror), not as this error.

`reason` names the stop and `manage_url` is where it is cleared. Today the only reason on this error is `overages_disabled`: a paid plan at zero that has not allowed usage past zero. Both are `None` (`null` in JS) against a server too old to send them, so treat them as optional rather than assuming they are set.

**How to recover:**

This error is permanent: retrying the same request fails the same way until one of these happens.

* **Turn overages on.** Only the account owner can, in the [Dashboard](https://docs.maximem.ai/dashboard/overview.md) under **Credits & Usage → Plan & billing**, or with `maximem-synap billing overages set --allow` from the [CLI](https://docs.maximem.ai/cli/commands.md#billing). The account needs an active paid subscription and a chargeable default card. New requests then continue, and usage past the allowance is billed per 1,000 credits.
* **Add credits.** Redeem a code with [`credits.redeem`](https://docs.maximem.ai/sdk-reference/credits/redeem), or request credits in the Dashboard.
* **Upgrade, or wait** for the next cycle's allowance.

If overages were on and this error appears, Synap may have turned them off because the card they depended on was removed or expired. Every member of the account is emailed when that happens.

**How to handle:**

```python Python theme={null}
from maximem_synap import InsufficientCreditsError

try:
    response = await sdk.memories.create(
        document=conversation_text,
        document_type="ai-chat-conversation",
        user_id=user_id,
        customer_id=customer_id,
    )
except InsufficientCreditsError as e:
    logger.error(
        "Insufficient credits (reason=%s): balance=%s, required=%s, manage=%s, recover=%s",
        e.reason, e.balance_credits, e.minimum_required_credits,
        e.manage_url, e.recovery_url
    )
    # Retrying will not help. Tell the operator to turn on overages
    # (account owner) or add credits, then resume the work.
```

```javascript JavaScript theme={null}
import { InsufficientCreditsError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: conversation_text,
    document_type: 'ai-chat-conversation',
    user_id: user_id,
    customer_id: customer_id,
  });
} catch (e) {
  if (!(e instanceof InsufficientCreditsError)) throw e;
  console.error('Insufficient credits (reason=%s): balance=%s, required=%s, manage=%s, recover=%s', e.reason, e.balanceCredits, e.requiredCredits, e.manageUrl, e.recoveryUrl);
    // Retrying will not help. Tell the operator to turn on overages
    // (account owner) or add credits, then resume the work.
}
```

```typescript TypeScript theme={null}
import { InsufficientCreditsError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: conversation_text,
    document_type: 'ai-chat-conversation',
    user_id: user_id,
    customer_id: customer_id,
  });
} catch (e) {
  if (!(e instanceof InsufficientCreditsError)) throw e;
  console.error('Insufficient credits (reason=%s): balance=%s, required=%s, manage=%s, recover=%s', e.reason, e.balanceCredits, e.requiredCredits, e.manageUrl, e.recoveryUrl);
    // Retrying will not help. Tell the operator to turn on overages
    // (account owner) or add credits, then resume the work.
}
```

**On the listening stream:** a credit refusal reaches `listen()` as a disconnect, not as a raised exception, because the stream is already running by then. The SDK stops the stream rather than reconnecting (a reconnect re-runs the same check against the same balance) and passes a reason of `credit_stop:<reason>` to your `on_disconnect` handler, for example `credit_stop:overages_disabled` or `credit_stop:trial_limit_reached`. Anything else still reconnects with backoff as before, and those reasons are unchanged.

```python Python theme={null}
def on_disconnect(reason: str) -> None:
    if reason.startswith("credit_stop:"):
        # Stopped for credits. Reconnecting will not help until the
        # account is topped up or overages are allowed.
        logger.error("Listening stopped: %s", reason)
        return
    logger.warning("Stream disconnected: %s", reason)

await sdk.instance.listen(on_disconnect=on_disconnect, on_context=handle_bundle)
```

```javascript JavaScript theme={null}
await sdk.instance.listen({
  onContext: handleBundle,
  onDisconnect: (reason) => {
    if (reason.startsWith('credit_stop:')) {
      // Stopped for credits. Reconnecting will not help until the
      // account is topped up or overages are allowed.
      console.error('Listening stopped: %s', reason);
      return;
    }
    console.warn('Stream disconnected: %s', reason);
  },
});
```

```typescript TypeScript theme={null}
await sdk.instance.listen({
  onContext: handleBundle,
  onDisconnect: (reason: string) => {
    if (reason.startsWith('credit_stop:')) {
      // Stopped for credits. Reconnecting will not help until the
      // account is topped up or overages are allowed.
      console.error('Listening stopped: %s', reason);
      return;
    }
    console.warn('Stream disconnected: %s', reason);
  },
});
```

### AgentUnavailableError

**AgentUnavailableError** `SynapTransientError`

Raised when the Synap agent backing the instance is temporarily unavailable. This is a transient error; the SDK will automatically retry.

**When it occurs:**

* The agent process is restarting or being redeployed
* Temporary resource contention on the backend

**How to handle:**

```python Python theme={null}
from maximem_synap import AgentUnavailableError

try:
    response = await sdk.memories.create(
        document=conversation_text,
        user_id=user_id,
        customer_id=customer_id
    )
except AgentUnavailableError as e:
    logger.warning(
        "Agent unavailable after all retries (correlation_id=%s)",
        e.correlation_id
    )
    # Queue for retry later
```

```javascript JavaScript theme={null}
import { AgentUnavailableError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: conversation_text,
    user_id: user_id,
    customer_id: customer_id,
  });
} catch (e) {
  if (!(e instanceof AgentUnavailableError)) throw e;
  console.warn('Agent unavailable after all retries (correlation_id=%s)', e.correlationId);
    // Queue for retry later
}
```

```typescript TypeScript theme={null}
import { AgentUnavailableError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: conversation_text,
    user_id: user_id,
    customer_id: customer_id,
  });
} catch (e) {
  if (!(e instanceof AgentUnavailableError)) throw e;
  console.warn('Agent unavailable after all retries (correlation_id=%s)', e.correlationId);
    // Queue for retry later
}
```

> [!NOTE]
>
> The SDK automatically retries `AgentUnavailableError` according to your configured retry policy. This error only surfaces to your code when all retry attempts are exhausted.

### ListeningAlreadyActiveError

**ListeningAlreadyActiveError** `SynapPermanentError`

Raised when you call `listen()` on an instance that already has an active listening stream. Only one stream can be active per SDK instance at a time.

**When it occurs:**

* Calling `listen()` a second time without first calling `stop_listening()`
* Duplicate initialization paths in your application

**How to handle:**

```python Python theme={null}
from maximem_synap import ListeningAlreadyActiveError

try:
    await sdk.instance.listen(on_context=on_event)
except ListeningAlreadyActiveError:
    logger.warning("Listening stream already active; skipping duplicate call")
    # No action needed; the existing stream is still running
```

```javascript JavaScript theme={null}
import { ListeningAlreadyActiveError, isSynapError } from '@maximem/synap-js-sdk';

try {
  await sdk.instance.listen({
    on_context: on_event,
  });
} catch (e) {
  if (!(e instanceof ListeningAlreadyActiveError)) throw e;
  console.warn('Listening stream already active; skipping duplicate call');
    // No action needed; the existing stream is still running
}
```

```typescript TypeScript theme={null}
import { ListeningAlreadyActiveError, isSynapError } from '@maximem/synap-js-sdk';

try {
  await sdk.instance.listen({
    on_context: on_event,
  });
} catch (e) {
  if (!(e instanceof ListeningAlreadyActiveError)) throw e;
  console.warn('Listening stream already active; skipping duplicate call');
    // No action needed; the existing stream is still running
}
```

### ListeningNotActiveError

**ListeningNotActiveError** `SynapPermanentError`

Raised by `send_message()` when no listening stream is currently active.

**When it occurs:**

* Calling `send_message()` before `listen()` has been called
* Calling `send_message()` after `stop_listening()`, or while the stream is down and has not yet reconnected

> [!NOTE]
>
> `stop_listening()` does **not** raise this. It is idempotent and a safe no-op when no stream is active, so it needs no guard.

**How to handle:**

```python Python theme={null}
from maximem_synap import ListeningNotActiveError

try:
    await sdk.instance.send_message(
        content=text,
        conversation_id=conversation_id,
        user_id=user_id,
        customer_id=customer_id,
    )
except ListeningNotActiveError:
    # Anticipation is an optimization: losing a signal event is not fatal.
    logger.debug("synap_stream_down; skipping anticipation event")
```

```javascript JavaScript theme={null}
import { ListeningNotActiveError, isSynapError } from '@maximem/synap-js-sdk';

try {
  await sdk.instance.send_message({
    content: text,
    conversation_id: conversation_id,
    user_id: user_id,
    customer_id: customer_id,
  });
} catch (e) {
  if (!(e instanceof ListeningNotActiveError)) throw e;
    // Anticipation is an optimization: losing a signal event is not fatal.
  console.debug('synap_stream_down; skipping anticipation event');
}
```

```typescript TypeScript theme={null}
import { ListeningNotActiveError, isSynapError } from '@maximem/synap-js-sdk';

try {
  await sdk.instance.send_message({
    content: text,
    conversation_id: conversation_id,
    user_id: user_id,
    customer_id: customer_id,
  });
} catch (e) {
  if (!(e instanceof ListeningNotActiveError)) throw e;
    // Anticipation is an optimization: losing a signal event is not fatal.
  console.debug('synap_stream_down; skipping anticipation event');
}
```

> [!TIP]
>
> In a long-lived server, guard with `if sdk.instance.is_listening:` rather than catching per call. That is what the framework integrations do: stream sends log and never raise.

## Stream health

The Listen stream fails in a way that is deliberately invisible to your application, so it needs different handling from the errors above.

| Condition | Behaviour |
| - | - |
| `listen()` fails at startup | **Python raises** (`AuthenticationError`, `SDKNotInitializedError`). The **TypeScript** SDK logs a console warning and falls back to HTTP. |
| Stream drops mid-run | `on_disconnect(reason)` fires; the SDK reconnects with exponential backoff (10 attempts, counter resets on each success). |
| Server closes at max lifetime (1 hour) | Routine. `on_reconnect(attempt)` fires. Not an error. |
| Per-instance/client quota exceeded | `RESOURCE_EXHAUSTED`, then a reconnect loop. Usually means one stream per session instead of one per process. |
| Reconnects exhausted | Stream stays down. **`fetch()` keeps working over REST**, and no exception ever reaches your code. |

> [!WARNING]
>
> A permanently dead stream is silent: retrieval still returns correct results, just slower. Do not infer stream health from your agent working. Export `sdk.instance.is_listening` to your health endpoint and alert when it stays false. See [Real-Time Anticipation in a Server](https://docs.maximem.ai/patterns/real-time-anticipation-server.md).

## Using correlation\_id

Every Synap error includes an optional `correlation_id` that uniquely identifies the failed request within Synap's distributed tracing system.

```python Python theme={null}
import uuid
from maximem_synap import SynapError

try:
    context = await sdk.conversation.context.fetch(
        conversation_id=str(uuid.uuid4())
    )
except SynapError as e:
    logger.error(
        "Synap error: %s | correlation_id: %s | type: %s",
        str(e),
        e.correlation_id,
        type(e).__name__
    )
```

```javascript JavaScript theme={null}
import { randomUUID } from 'node:crypto';
import { SynapError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
  });
} catch (e) {
  if (!(e instanceof SynapError)) throw e;
  console.error(
    'Synap error: %s | correlation_id: %s | type: %s',
    String(e), e.correlationId, e.constructor.name,
  );
}
```

```typescript TypeScript theme={null}
import { randomUUID } from 'node:crypto';
import { SynapError, isSynapError } from '@maximem/synap-js-sdk';

try {
  const context = await sdk.conversation.context.fetch({
    conversation_id: randomUUID(),
  });
} catch (e) {
  if (!(e instanceof SynapError)) throw e;
  console.error(
    'Synap error: %s | correlation_id: %s | type: %s',
    String(e), e.correlationId, e.constructor.name,
  );
}
```

> [!TIP]
>
> Always log the `correlation_id` from errors. Synap support can use it to trace the exact request path through the backend, including which pipeline stages were involved, what data was processed, and where the failure occurred.

## Retry Policy Configuration

The SDK's built-in retry policy handles transient errors automatically. You can customize the retry behavior through `RetryPolicy` in your `SDKConfig`.

```python Python theme={null}
from maximem_synap import SDKConfig, RetryPolicy

config = SDKConfig(
    retry_policy=RetryPolicy(
        max_attempts=5,               # Total attempts (1 initial + 4 retries)
        backoff_base=1.0,             # Base delay in seconds
        backoff_max=10.0,             # Maximum delay between retries
        backoff_jitter=True,          # Add random jitter to prevent thundering herd
        retryable_errors=[            # Error types to retry
            "NetworkTimeoutError",
            "RateLimitError",
            "ServiceUnavailableError",
            "SynapTransientError"
        ]
    )
)
```

```javascript JavaScript theme={null}
// No SDKConfig wrapper: the policy is an option on the client.
const sdk = new SynapClient({
  retryPolicy: {
    maxAttempts: 5,      // Total attempts (1 initial + 4 retries)
    backoffBase: 1.0,    // Base delay in seconds
    backoffMax: 10.0,    // Maximum delay between retries
    backoffJitter: true, // Add random jitter to prevent thundering herd
  },
});
```

```typescript TypeScript theme={null}
import { SynapClient, type RetryPolicy } from '@maximem/synap-js-sdk';

const retryPolicy: RetryPolicy = {
  maxAttempts: 5,      // Total attempts (1 initial + 4 retries)
  backoffBase: 1.0,    // Base delay in seconds
  backoffMax: 10.0,    // Maximum delay between retries
  backoffJitter: true, // Add random jitter to prevent thundering herd
};

const sdk = new SynapClient({ retryPolicy });
```

> [!NOTE]
>
> **JavaScript decides this differently, on purpose.** There is no
> `retryable_errors` list: every transient error is retried, and a
> non-idempotent call whose outcome is unknown is not, whatever its type. That
> second rule is what stops a lost response on `memories.create` from ingesting
> and billing the same content twice, and a per-error list could switch it off.
> To handle rate limits yourself, catch `RateLimitError` at the call site.

### Retry Behavior

The SDK uses exponential backoff with optional jitter:

```
Attempt 1: Immediate
Attempt 2: backoff_base * 2^0 = 1.0s  (± jitter)
Attempt 3: backoff_base * 2^1 = 2.0s  (± jitter)
Attempt 4: backoff_base * 2^2 = 4.0s  (± jitter)
Attempt 5: backoff_base * 2^3 = 8.0s  (± jitter, capped at backoff_max)
```

For `RateLimitError`, the SDK respects the `retry_after_seconds` value instead of the exponential backoff, waiting the exact duration specified by the server.

### Disabling Retries

To disable automatic retries entirely (useful for testing or when you implement your own retry logic):

```python Python theme={null}
config = SDKConfig(retry_policy=None)
```

```javascript JavaScript theme={null}
const sdk = new SynapClient({ retryPolicy: null });
```

```typescript TypeScript theme={null}
const sdk = new SynapClient({ retryPolicy: null });
```

### Customizing Retryable Errors

By default, all four transient error types are retried (`NetworkTimeoutError`, `RateLimitError`, `ServiceUnavailableError`, and `AgentUnavailableError`). Listing the base `SynapTransientError` in `retryable_errors` covers every transient subtype, including any added in future SDK releases. You can customize this list, though adding permanent errors is generally not recommended.

```python theme={null}
config = SDKConfig(
    retry_policy=RetryPolicy(
        retryable_errors=[
            "NetworkTimeoutError",
            "ServiceUnavailableError"
            # Removed RateLimitError, handle rate limits manually
        ]
    )
)
```

> [!NOTE]
>
> **Python only, deliberately.** JavaScript retries every transient error and
> never a non-idempotent call whose outcome is unknown. Narrowing that by error
> type could re-enable a retry that ingests and bills the same content twice,
> so the list is not offered. Catch `RateLimitError` at the call site instead.

## Common Error Handling Patterns

### Catch-All with Transient/Permanent Distinction

```python Python theme={null}
from maximem_synap import (
    SynapError,
    SynapTransientError,
    SynapPermanentError,
)

try:
    response = await sdk.memories.create(
        document=conversation_text,
        document_type="ai-chat-conversation",
        user_id=user_id,
        customer_id=customer_id,
        mode="long-range",
    )
except SynapTransientError as e:
    # All retries exhausted for a transient error
    logger.warning(
        "Transient error after retries: %s (correlation_id=%s)",
        e, e.correlation_id
    )
    # Queue for retry later, or degrade gracefully
    await retry_queue.enqueue(conversation_text, user_id)

except SynapPermanentError as e:
    # Something is fundamentally wrong
    logger.error(
        "Permanent error: %s (correlation_id=%s)",
        e, e.correlation_id
    )
    # Alert, fix the issue, do not retry as-is
    raise

except SynapError as e:
    # Catch-all for any unexpected Synap error
    logger.error("Unexpected Synap error: %s", e)
    raise
```

```javascript JavaScript theme={null}
import {
  SynapError,
  TransientError,
  PermanentError,
} from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: conversationText,
    document_type: 'ai-chat-conversation',
    user_id: userId,
    customer_id: customerId,
    mode: 'long-range',
  });
} catch (e) {
  // Python has one `except` per class; JavaScript has one `catch`, so the
  // branches move inside it. Order matters the same way: most specific first.
  if (e instanceof TransientError) {
    // All retries exhausted for a transient error
    console.warn(
      'Transient error after retries: %s (correlation_id=%s)',
      e, e.correlationId,
    );
    // Queue for retry later, or degrade gracefully
    await retryQueue.enqueue(conversationText, userId);
  } else if (e instanceof PermanentError) {
    // Something is fundamentally wrong
    console.error('Permanent error: %s (correlation_id=%s)', e, e.correlationId);
    // Alert, fix the issue, do not retry as-is
    throw e;
  } else if (e instanceof SynapError) {
    // Catch-all for any unexpected Synap error
    console.error('Unexpected Synap error: %s', e);
    throw e;
  } else {
    // Not ours: never swallow a bug in your own code as "Synap was down".
    throw e;
  }
}
```

```typescript TypeScript theme={null}
import {
  SynapError,
  TransientError,
  PermanentError,
} from '@maximem/synap-js-sdk';

try {
  const response = await sdk.memories.create({
    document: conversationText,
    document_type: 'ai-chat-conversation',
    user_id: userId,
    customer_id: customerId,
    mode: 'long-range',
  });
} catch (e) {
  // Python has one `except` per class; JavaScript has one `catch`, so the
  // branches move inside it. Order matters the same way: most specific first.
  if (e instanceof TransientError) {
    // All retries exhausted for a transient error
    console.warn(
      'Transient error after retries: %s (correlation_id=%s)',
      e, e.correlationId,
    );
    // Queue for retry later, or degrade gracefully
    await retryQueue.enqueue(conversationText, userId);
  } else if (e instanceof PermanentError) {
    // Something is fundamentally wrong
    console.error('Permanent error: %s (correlation_id=%s)', e, e.correlationId);
    // Alert, fix the issue, do not retry as-is
    throw e;
  } else if (e instanceof SynapError) {
    // Catch-all for any unexpected Synap error
    console.error('Unexpected Synap error: %s', e);
    throw e;
  } else {
    // Not ours: never swallow a bug in your own code as "Synap was down".
    throw e;
  }
}
```

### Per-Operation Error Handling

```python Python theme={null}
from maximem_synap import (
    InvalidInputError,
    NetworkTimeoutError,
    RateLimitError,
    SynapError,
)

async def safe_fetch_context(conversation_id: str, query: str):
    """Fetch context with graceful degradation."""
    try:
        return await sdk.conversation.context.fetch(
            conversation_id=conversation_id,
            search_query=[query],
            mode="fast"
        )

    except InvalidInputError:
        logger.info("Malformed conversation_id %s, skipping memory", conversation_id)
        return None

    except NetworkTimeoutError:
        logger.warning("Timeout fetching context, proceeding without memory")
        return None

    except RateLimitError as e:
        logger.warning(
            "Rate limited, retry after %ds", e.retry_after_seconds
        )
        return None

    except SynapError as e:
        logger.error(
            "Unexpected error fetching context: %s (correlation_id=%s)",
            e, e.correlation_id
        )
        return None
```

```javascript JavaScript theme={null}
import {
  InvalidInputError,
  NetworkTimeoutError,
  RateLimitError,
  SynapError,
} from '@maximem/synap-js-sdk';

async function safeFetchContext(conversationId, query) {
  // Fetch context with graceful degradation.
  try {
    return await sdk.conversation.context.fetch({
      conversation_id: conversationId,
      search_query: [query],
      mode: 'fast',
    });
  } catch (e) {
    if (e instanceof InvalidInputError) {
      console.info('Malformed conversation_id %s, skipping memory', conversationId);
      return null;
    }
    if (e instanceof NetworkTimeoutError) {
      console.warn('Timeout fetching context, proceeding without memory');
      return null;
    }
    if (e instanceof RateLimitError) {
      console.warn('Rate limited, retry after %ds', e.retryAfterSeconds);
      return null;
    }
    if (e instanceof SynapError) {
      console.error(
        'Unexpected error fetching context: %s (correlation_id=%s)',
        e, e.correlationId,
      );
      return null;
    }
    throw e;   // not ours
  }
}
```

```typescript TypeScript theme={null}
import {
  InvalidInputError,
  NetworkTimeoutError,
  RateLimitError,
  SynapError,
  type RawContext,
} from '@maximem/synap-js-sdk';

async function safeFetchContext(
  conversationId: string,
  query: string,
): Promise<RawContext | null> {
  // Fetch context with graceful degradation.
  try {
    return await sdk.conversation.context.fetch({
      conversation_id: conversationId,
      search_query: [query],
      mode: 'fast',
    });
  } catch (e) {
    if (e instanceof InvalidInputError) {
      console.info('Malformed conversation_id %s, skipping memory', conversationId);
      return null;
    }
    if (e instanceof NetworkTimeoutError) {
      console.warn('Timeout fetching context, proceeding without memory');
      return null;
    }
    if (e instanceof RateLimitError) {
      console.warn('Rate limited, retry after %ds', e.retryAfterSeconds);
      return null;
    }
    if (e instanceof SynapError) {
      console.error(
        'Unexpected error fetching context: %s (correlation_id=%s)',
        e, e.correlationId,
      );
      return null;
    }
    throw e;   // not ours
  }
}
```

### Initialization Error Handling

```python Python theme={null}
from maximem_synap import (
    AuthenticationError,
    InvalidInputError,
    NetworkTimeoutError,
    SynapError,
)

async def initialize_with_fallback():
    """Initialize SDK with comprehensive error handling."""
    try:
        await sdk.initialize()
        return True

    except InvalidInputError:
        logger.error("Invalid instance ID. Check your configuration.")
        return False

    except AuthenticationError as e:
        logger.error(
            "Auth failed (no API key or invalid credentials): %s (correlation_id=%s)",
            e, e.correlation_id
        )
        return False

    except NetworkTimeoutError:
        logger.error("Cannot reach Synap Cloud. Check network connectivity.")
        return False

    except SynapError as e:
        logger.error(
            "Unexpected initialization error: %s (correlation_id=%s)",
            e, e.correlation_id
        )
        return False
```

```javascript JavaScript theme={null}
import {
  AuthenticationError,
  InvalidInputError,
  NetworkTimeoutError,
  SynapError,
} from '@maximem/synap-js-sdk';

async function initializeWithFallback() {
  // Initialize SDK with comprehensive error handling.
  try {
    await sdk.initialize();
    return true;
  } catch (e) {
    if (e instanceof InvalidInputError) {
      console.error('Invalid instance ID. Check your configuration.');
      return false;
    }
    if (e instanceof AuthenticationError) {
      console.error(
        'Auth failed (no API key or invalid credentials): %s (correlation_id=%s)',
        e, e.correlationId,
      );
      return false;
    }
    if (e instanceof NetworkTimeoutError) {
      console.error('Cannot reach Synap Cloud. Check network connectivity.');
      return false;
    }
    if (e instanceof SynapError) {
      console.error(
        'Unexpected initialization error: %s (correlation_id=%s)',
        e, e.correlationId,
      );
      return false;
    }
    throw e;   // not ours
  }
}
```

```typescript TypeScript theme={null}
import {
  AuthenticationError,
  InvalidInputError,
  NetworkTimeoutError,
  SynapError,
} from '@maximem/synap-js-sdk';

async function initializeWithFallback(): Promise<boolean> {
  // Initialize SDK with comprehensive error handling.
  try {
    await sdk.initialize();
    return true;
  } catch (e) {
    if (e instanceof InvalidInputError) {
      console.error('Invalid instance ID. Check your configuration.');
      return false;
    }
    if (e instanceof AuthenticationError) {
      console.error(
        'Auth failed (no API key or invalid credentials): %s (correlation_id=%s)',
        e, e.correlationId,
      );
      return false;
    }
    if (e instanceof NetworkTimeoutError) {
      console.error('Cannot reach Synap Cloud. Check network connectivity.');
      return false;
    }
    if (e instanceof SynapError) {
      console.error(
        'Unexpected initialization error: %s (correlation_id=%s)',
        e, e.correlationId,
      );
      return false;
    }
    throw e;   // not ours
  }
}
```

## Full error reference

The hierarchy and handling patterns above cover how to catch and respond to each error. For the at-a-glance catalog (every SDK exception class with its transient/permanent type and common cause) see [SDK Reference: Error handling](https://docs.maximem.ai/sdk-reference/overview.md#error-handling). For the server-side wire codes those exceptions wrap (HTTP status, machine-readable `code`, and `details` shape) see [Error Codes](https://docs.maximem.ai/sdk-reference/errors.md).

## Next Steps

> [card] [SDK Configuration](https://docs.maximem.ai/sdk/configuration.md)
>
> Customize retry policies, timeouts, and other SDK settings.

> [card] [Initializing the SDK](https://docs.maximem.ai/sdk/initialization.md)
>
> Set up the SDK with proper error handling from the start.

> [card] [Support](https://docs.maximem.ai/resources/support.md)
>
> Contact Synap support with correlation IDs for issue resolution.

> [card] [FAQ](https://docs.maximem.ai/resources/faq.md)
>
> Common questions about errors and troubleshooting.

## JavaScript: typed error handling

Error classes are real classes, so `instanceof` narrowing works, and each carries a stable `.code` and a `.transient` flag:

```ts theme={null}
import {
  RateLimitError,
  AuthenticationError,
  InsufficientCreditsError,
  isSynapError,
} from "@maximem/synap-js-sdk";

try {
  await synap.user.context.fetch({ user_id, customer_id });
} catch (error) {
  if (!isSynapError(error)) throw error;

  if (error instanceof RateLimitError) {
    console.warn(`Retry after ${error.retryAfterSeconds}s`);
  } else if (error instanceof AuthenticationError) {
    console.error("Check SYNAP_API_KEY");
  } else if (error instanceof InsufficientCreditsError) {
    console.error(
      `Short ${error.requiredCredits} credits (balance ${error.balanceCredits}). ` +
      `Top up: ${error.recoveryUrl}  Redeem: ${error.redeemUrl}`,
    );
  }
}
```

Transient errors are retried automatically. Ingestion is deliberately **not** retried when a failure leaves the outcome unknown, because a retry would store and bill twice.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.