# Error Handling

The Platform SDK provides typed error classes for every HTTP error category. All errors extend `AmigoError`, which includes the HTTP status code and a descriptive message.

## Error Types

```typescript
import { errors } from '@amigo-ai/platform-sdk'

// Available error classes:
errors.AmigoError           // Base error class, all SDK errors extend this
errors.AuthenticationError  // 401, invalid or expired API key
errors.NotFoundError        // 404, resource does not exist
errors.BadRequestError      // 400, invalid request format or parameters
errors.ValidationError      // 422, request validation failed
errors.ConflictError        // 409, resource conflict (for example, duplicate name)
errors.NetworkError         // Connection issues, timeouts
```

Every error exposes:

| Property  | Type                  | Description                                     |
| --------- | --------------------- | ----------------------------------------------- |
| `message` | `string`              | Human-readable error message                    |
| `status`  | `number \| undefined` | HTTP status code (undefined for network errors) |
| `cause`   | `unknown`             | Underlying cause for network errors             |

## Basic Error Handling

```typescript
import { AmigoClient, errors } 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 errors.AuthenticationError) {
      console.error('Authentication failed. Check your API key.')

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

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

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

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

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

    } else if (error instanceof errors.AmigoError) {
      console.error(`API error (${error.status}): ${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 errors.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 errors.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 errors.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 errors.ValidationError) {
    console.error(`Validation failed: ${error.message}`)
  }
}
```

## Built-in Retry Logic

The SDK automatically retries failed requests for transient failures:

| Error Type              | Retry Strategy                    |
| ----------------------- | --------------------------------- |
| **Network errors**      | Automatic exponential backoff     |
| **Rate limiting (429)** | Automatic retry with proper delay |
| **Server errors (5xx)** | Intelligent retry with backoff    |

{% hint style="info" %}
**Automatic Retries.** You don't need to implement retry logic manually. The SDK handles retries for you. If a `NetworkError` reaches your catch block, all retry attempts have been exhausted.
{% endhint %}

{% @mermaid/diagram content="%%{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{Retry Count < Max?}
Check -->|5xx Server Error| Retry
Check -->|429 Rate Limit| Retry
Check -->|4xx Client Error| Fail[Throw Typed Error]

Retry -->|Yes| Wait[Exponential Backoff]
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. **Trust built-in retries.** Only add custom retry logic for business-level failures, not HTTP errors.
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/platform-api/agents.md)**.** Agent management reference.
* [**Analytics & Observability**](/developer-guide/platform-api/platform-api/analytics.md)**.** Usage monitoring.


---

# Agent Instructions: 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:

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

The question should be specific, self-contained, and written in natural language.
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.
