> For the complete documentation index, see [llms.txt](https://titan-exchange.gitbook.io/titan/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://titan-exchange.gitbook.io/titan/developer-doc/swap-api/reference/error-codes.md).

# Error Codes

When a request fails, the server returns a `ResponseError` with a numeric `code` and a human-readable `message`. On **Titan Direct**, errors arrive as an `Error` variant of `ServerMessage`. On **Titan Gateway**, errors are returned as HTTP status codes with a MessagePack body.

## Error response format

{% tabs %}
{% tab title="Titan Direct" %}

```typescript
{
  Error: {
    requestId: number;   // Matches the ID of the original request
    code: number;        // Numeric error code for programmatic handling
    message: string;     // Human-readable description for logging/debugging
  }
}
```

{% hint style="info" %}
The `message` field contains a specific, actionable description of the error. **Use the `code` for programmatic handling** and the `message` for logging and debugging.
{% endhint %}
{% endtab %}

{% tab title="Titan Gateway" %}

| Status        | Description                                                                      |
| ------------- | -------------------------------------------------------------------------------- |
| `400`         | Invalid parameters — malformed pubkey, missing required field, or invalid value. |
| `401`         | Missing or invalid authentication token.                                         |
| `404`         | No routes found for this swap pair.                                              |
| {% endtab %}  |                                                                                  |
| {% endtabs %} |                                                                                  |

## Stream errors

Streams can end with an error via the `StreamEnd` message:

```typescript
{
  StreamEnd: {
    id: number;              // The stream ID that has ended
    errorCode?: number;      // Present only if the stream ended due to an error
    errorMessage?: string;   // Human-readable reason for the error, if any
  }
}
```

{% hint style="warning" %}
A `StreamEnd` **without** `errorCode` indicates a clean shutdown (e.g. after `StopStream`). A `StreamEnd` **with** `errorCode` means something went wrong and you should inspect the message.
{% endhint %}

***

## WebSocket close codes

The server may close the WebSocket connection with a specific close code:

* **`3002`** — **Protocol error.** The client sent an invalid or unsupported protocol string during negotiation, or violated the wire protocol after connecting. Reconnect with a valid `Sec-WebSocket-Protocol` header.
* **`1000`** — Normal closure. The server shut down gracefully.
* **`1001`** — Going away. The server is restarting or shutting down for maintenance.

***

## SDK error classes

**If you're using the** [**`@titanexchange/sdk-ts`**](https://www.npmjs.com/package/@titanexchange/sdk-ts) **TypeScript SDK**, errors are thrown as typed classes you can catch and inspect:

### Connection errors

* **`ConnectionClosed`** — The WebSocket was closed unexpectedly. Properties: `code` (close code), `reason` (close reason string), `wasClean` (whether the close was clean).
* **`ConnectionError`** — Failed to establish or maintain the WebSocket connection. Property: `cause` (underlying error).
* **`InvalidProtocolError`** — The server selected an unsupported protocol string during negotiation. Property: the invalid protocol string.

### RPC errors

* **`ErrorResponse`** — The server returned an error for a specific request. Properties: `response.code` (numeric error code), `response.message` (human-readable description), `response.requestId`.
* **`StreamError`** — A stream ended with an error. Properties: `streamId`, `errorCode`, `errorMessage`.
* **`ProtocolError`** — A wire-level protocol violation. Properties: `reason`, `data`.

### Codec errors

* **`DecodeError`** — Failed to decode a MessagePack message. Properties: `reason`, `value`.

### Recommended pattern

```typescript
import { ErrorResponse, StreamError, ConnectionClosed } from '@titanexchange/sdk-ts';

try {
  // ... SDK operations
} catch (err) {
  if (err instanceof ErrorResponse) {
    // Server rejected the request — check code for programmatic handling
    console.error(`RPC error ${err.response.code}: ${err.response.message}`);
  } else if (err instanceof StreamError) {
    // Stream ended abnormally — re-open it
    console.error(`Stream ${err.streamId} error: ${err.errorMessage}`);
  } else if (err instanceof ConnectionClosed) {
    // WebSocket dropped — reconnect with backoff
    console.warn(`Connection closed: code=${err.code}, clean=${err.wasClean}`);
  }
}
```

***

## Handling errors

* **Authentication errors** — Verify your token is valid, not expired, and includes the required JWT claims (`iss`, `sub`, `aud`, `exp`, `iat`). See [Connection & Negotiation](/titan/developer-doc/swap-api/reference/direct/connection.md).
* **Invalid parameters** — Check that pubkeys are valid base58, amounts are positive integers, and all required fields are present.
* **No routes found** — The swap pair may have insufficient liquidity, or routing constraints (`dexes`, `excludeDexes`, `onlyDirectRoutes`) may be too restrictive. **Try relaxing your filters** before assuming the pair is unsupported.
* **Stream errors** — When a stream ends unexpectedly, re-open it. **Stream IDs from a previous connection are not valid after reconnect.**

For reconnection patterns, see [Error Handling & Reconnect](/titan/developer-doc/swap-api/guides/error-handling.md).

***

## Related pages

* [Error Handling & Reconnect](/titan/developer-doc/swap-api/guides/error-handling.md) — retry strategies, backoff logic, and reconnect patterns
* [Wire Protocol](/titan/developer-doc/swap-api/reference/wire-protocol.md) — message envelope format and framing details
* [Types Reference](/titan/developer-doc/swap-api/reference/types.md) — Types Reference — index of all type definitions
