> For the complete documentation index, see [llms.txt](https://docs.amigo.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.amigo.ai/developer-guide/platform-api/platform-sdk/error-handling.md).

# Error Handling

The Platform SDK provides typed request-path errors for common HTTP statuses plus transport, parsing, and configuration failures. These classes extend `AmigoError`, which includes a descriptive message and an HTTP status code when one is available. Webhook, reconnecting WebSocket, and workspace-event-stream helpers expose separate native `Error` subclasses with helper-specific fields.

## Error Types

```typescript
import {
  AmigoError,
  AuthenticationError,
  PermissionError,
  NotFoundError,
  BadRequestError,
  ValidationError,
  ConflictError,
  RateLimitError,
  ServerError,
  ServiceUnavailableError,
  NetworkError,
  RequestTimeoutError,
  ParseError,
  ConfigurationError,
} from '@amigo-ai/platform-sdk'

// Available error classes:
AmigoError              // Base class for request-path SDK errors
AuthenticationError     // 401, invalid or expired API key
PermissionError         // 403, insufficient permissions
NotFoundError           // 404, resource does not exist
BadRequestError         // 400, invalid request format or parameters
ValidationError         // 422, request validation failed
ConflictError           // 409, resource conflict (for example, duplicate name)
RateLimitError          // 429, rate limited (exposes .retryAfter)
ServerError             // Fallback for other HTTP statuses, including unmapped 4xx and 5xx responses
ServiceUnavailableError // 503, service temporarily unavailable (extends ServerError)
NetworkError            // Connection failure, no HTTP status available
RequestTimeoutError     // Request exceeded configured timeout (exposes .timeoutMs, extends NetworkError)
ParseError              // Response body could not be parsed (exposes .body)
ConfigurationError      // Invalid client config (e.g. missing apiKey or workspaceId)
```

The SDK also exports convenience type guards such as `isNotFoundError`, `isRateLimitError`, `isAuthenticationError`, and `isAmigoError` for narrowing without `instanceof`.

Every `AmigoError` exposes:

| Property     | Type                  | Description                                         |
| ------------ | --------------------- | --------------------------------------------------- |
| `message`    | `string`              | Human-readable error message                        |
| `statusCode` | `number \| undefined` | HTTP status code (undefined for network errors)     |
| `errorCode`  | `string \| undefined` | Machine-readable error code from the API            |
| `requestId`  | `string \| undefined` | Request identifier for support and tracing          |
| `detail`     | `string \| undefined` | Additional detail about the error, when available   |
| `errorBody`  | `object \| undefined` | Parsed error response body, when one was returned   |
| `rawBody`    | `string \| undefined` | Raw response body (truncated to 8 KB) for debugging |

`NetworkError` and `RequestTimeoutError` additionally expose a `cause` property carrying the underlying connection error.

`WebhookVerificationError`, `ReconnectingWebSocketError`, and `WorkspaceEventStreamError` extend the native `Error` class rather than `AmigoError`. Handle them through their corresponding helper APIs; they do not share the HTTP response fields listed above.

## Basic Error Handling

```typescript
import {
  AmigoClient,
  AmigoError,
  AuthenticationError,
  NotFoundError,
  BadRequestError,
  ValidationError,
  ConflictError,
  NetworkError,
} from '@amigo-ai/platform-sdk'

const client = new AmigoClient({
  apiKey: process.env.AMIGO_API_KEY!,
  workspaceId: process.env.AMIGO_WORKSPACE_ID!,
})

async function fetchAgent(agentId: string) {
  try {
    const agent = await client.agents.get(agentId)
    console.log(`Agent: ${agent.name}`)

  } catch (error) {
    if (error instanceof AuthenticationError) {
      console.error('Authentication failed. Check your API key.')

    } else if (error instanceof NotFoundError) {
      console.error(`Agent ${agentId} does not exist`)

    } else if (error instanceof BadRequestError) {
      console.error(`Invalid request: ${error.message}`)

    } else if (error instanceof ValidationError) {
      console.error(`Validation failed: ${error.message}`)

    } else if (error instanceof ConflictError) {
      console.error(`Conflict: ${error.message}`)

    } else if (error instanceof NetworkError) {
      console.error(`Network error: ${error.message}`)
      // GET requests are retried automatically. If this throws, retries are exhausted.

    } else if (error instanceof AmigoError) {
      console.error(`API error (${error.statusCode}): ${error.message}`)

    } else {
      console.error('Unexpected error:', error)
    }
  }
}
```

## Common Error Scenarios

### Authentication Errors

`AuthenticationError` (HTTP 401) is thrown when the API key is invalid or has expired.

```typescript
try {
  await client.agents.list()
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Regenerate the API key in the Amigo dashboard
    console.error('API key is invalid or expired')
  }
}
```

### Not Found Errors

`NotFoundError` (HTTP 404) is thrown when a resource ID does not exist in the workspace.

```typescript
try {
  const agent = await client.agents.get('non-existent-id')
} catch (error) {
  if (error instanceof NotFoundError) {
    // Fall back to a default agent or return null
    console.error('Agent not found. It may have been deleted.')
  }
}
```

### Conflict Errors

`ConflictError` (HTTP 409) commonly occurs when creating a resource with a name that already exists. These are often recoverable.

```typescript
try {
  await client.agents.create({ name: 'My Agent', description: '' })
} catch (error) {
  if (error instanceof ConflictError) {
    // Try a different name or fetch the existing resource
    console.error('An agent with this name already exists')
  }
}
```

### Validation Errors

`ValidationError` (HTTP 422) indicates the request body failed server-side validation. Check the error message for field-level details.

```typescript
try {
  await client.agents.create({ name: '', description: '' }) // empty name
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(`Validation failed: ${error.message}`)
  }
}
```

## Built-in Retry Logic

The SDK automatically retries transient failures with exponential backoff and full jitter (base delay 250 ms, capped at 30 s, 3 attempts total by default; tune with the `retry` or `maxRetries` client options):

| Failure                                             | Retry Behavior                                                                                                 |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| **Network errors**                                  | Retried with backoff for `GET`, `HEAD`, and `OPTIONS` requests                                                 |
| **Rate limiting (429)**                             | `GET` and `HEAD` retry and honor `Retry-After` when present. `POST` retries only when `Retry-After` is present |
| **Transient HTTP errors (408, 500, 502, 503, 504)** | Retried with backoff for `GET` and `HEAD` requests                                                             |
| **Other methods**                                   | `OPTIONS`, `PUT`, `PATCH`, and `DELETE` responses are not retried automatically                                |
| **Request timeouts**                                | Not retried; thrown immediately as `RequestTimeoutError`                                                       |

{% hint style="info" %}
**Automatic Retries.** The SDK retries eligible `GET` and `HEAD` responses and network failures for `GET`, `HEAD`, and `OPTIONS`. A `POST` response is retried only for `429` with `Retry-After`; other write requests are not retried automatically. If an eligible failure reaches your catch block, the configured attempts are exhausted.
{% endhint %}

```mermaid
%%{init: {"flowchart": {"useMaxWidth": true, "nodeSpacing": 30, "rankSpacing": 40}, "theme": "base", "themeVariables": {"primaryColor": "#D4E2E7", "primaryTextColor": "#100F0F", "primaryBorderColor": "#083241", "lineColor": "#575452", "textColor": "#100F0F", "clusterBkg": "#F1EAE7", "clusterBorder": "#D7D2D0"}}}%%
flowchart TB
    Start[API Request] --> Try[Execute Request]
    Try --> Check{Success?}

    Check -->|200 OK| Success[Return Response]
    Check -->|Network Error| Retry{Retryable for method<br/>and attempts remain?}
    Check -->|408/5xx Transient Error| Retry
    Check -->|429 Rate Limit| Retry
    Check -->|Other 4xx Client Error| Fail[Throw Typed Error]

    Retry -->|Yes| Wait[Exponential Backoff<br/>or Retry-After]
    Wait --> Try
    Retry -->|No| Fail

    style Success fill:#DDE3DB,stroke:#2c3827,color:#100F0F,stroke-width:2px
    style Fail fill:#F0DDD9,stroke:#AA412A,color:#100F0F,stroke-width:2px
    style Wait fill:#F0DDD9,stroke:#AA412A,color:#100F0F,stroke-width:2px
    style Try fill:#D4E2E7,stroke:#083241,color:#100F0F,stroke-width:2px
```

## Best Practices

1. **Catch specific error types.** Handle `NotFoundError` differently from `AuthenticationError`.
2. **Log with context.** Include the resource ID and operation in error logs.
3. **Treat `ConflictError` as recoverable.** It often means the resource already exists, so you can fetch it instead.
4. **Match recovery to the method.** Built-in response retries cover eligible `GET` and `HEAD` failures; network retries also cover `OPTIONS`. The SDK does not retry write requests on network failure, and only retries `POST` responses for `429` with `Retry-After`. Add idempotency-aware handling for writes when needed.
5. **Validate locally first.** Use TypeScript types to catch missing required fields before they become `ValidationError`s at runtime.

## Next Steps

* [**Quickstart**](/developer-guide/platform-api/platform-sdk/quickstart.md)**.** First API calls with proper error handling.
* [**Agents**](/developer-guide/platform-api/workspaces/agents.md)**.** Agent management reference.
* [**Analytics & Observability**](/developer-guide/platform-api/safety/analytics.md)**.** Usage monitoring.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.amigo.ai/developer-guide/platform-api/platform-sdk/error-handling.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
