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

# Error Handling

> Handle errors gracefully with typed error classes

The Orchata SDK throws typed errors for different scenarios, making error handling straightforward and type-safe.

## Error Types

Import error classes to handle specific error types:

```typescript theme={null}
import {
  Orchata,
  OrchataError,
  AuthenticationError,
  NotFoundError,
  RateLimitError,
  BadRequestError,
  PermissionDeniedError,
  ConflictError,
  UnprocessableEntityError,
  InternalServerError,
  TimeoutError,
  ConnectionError
} from '@orchata-ai/sdk';
```

## Basic Error Handling

Handle errors with try-catch blocks:

```typescript theme={null}
import { Orchata, AuthenticationError, NotFoundError } from '@orchata-ai/sdk';

const client = new Orchata({ apiKey: 'oai_xxx' });

try {
  const { results } = await client.query({
    spaceIds: 'space_123',
    query: 'test'
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof NotFoundError) {
    console.error('Space not found');
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
  } else if (error instanceof OrchataError) {
    console.error(`API error: ${error.message} (${error.status})`);
  } else {
    throw error; // Re-throw unknown errors
  }
}
```

## Error Types Reference

| Error                      | Status | Description                                    |
| -------------------------- | ------ | ---------------------------------------------- |
| `BadRequestError`          | 400    | Invalid request parameters                     |
| `AuthenticationError`      | 401    | Missing or invalid API key                     |
| `PermissionDeniedError`    | 403    | Insufficient permissions                       |
| `NotFoundError`            | 404    | Resource not found                             |
| `ConflictError`            | 409    | Resource conflict (e.g., duplicate space name) |
| `UnprocessableEntityError` | 422    | Validation error                               |
| `RateLimitError`           | 429    | Too many requests                              |
| `InternalServerError`      | 5xx    | Server error                                   |
| `TimeoutError`             | -      | Request timeout                                |
| `ConnectionError`          | -      | Network connectivity issue                     |

## Rate Limit Handling

Handle rate limits with retry logic:

```typescript theme={null}
import { Orchata, RateLimitError } from '@orchata-ai/sdk';

async function queryWithRetry(client: Orchata, query: string, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await client.query({
        spaceIds: 'space_123',
        query
      });
    } catch (error) {
      if (error instanceof RateLimitError) {
        const waitTime = error.retryAfter * 1000; // Convert to milliseconds
        console.log(`Rate limited. Waiting ${waitTime}ms before retry...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }
      throw error; // Re-throw non-rate-limit errors
    }
  }
  throw new Error('Max retries exceeded');
}
```

## Error Properties

All error instances include useful properties:

```typescript theme={null}
try {
  await client.spaces.get('invalid_id');
} catch (error) {
  if (error instanceof OrchataError) {
    console.error(error.message); // Human-readable error message
    console.error(error.status); // HTTP status code
    console.error(error.statusCode); // Alias for status
    console.error(error.code); // Error code (if available)
  }
}
```

### RateLimitError Properties

`RateLimitError` includes additional properties:

```typescript theme={null}
if (error instanceof RateLimitError) {
  console.error(error.retryAfter); // Seconds to wait before retrying
  console.error(error.limit); // Rate limit value
  console.error(error.remaining); // Remaining requests
  console.error(error.reset); // Timestamp when limit resets
}
```

## Type-Safe Error Handling

TypeScript provides full type safety for error handling:

```typescript theme={null}
import { Orchata, OrchataError } from '@orchata-ai/sdk';

async function safeQuery(client: Orchata, query: string) {
  try {
    const result = await client.query({
      spaceIds: 'space_123',
      query
    });
    return { success: true, data: result };
  } catch (error) {
    if (error instanceof OrchataError) {
      return {
        success: false,
        error: {
          message: error.message,
          status: error.status,
          code: error.code
        }
      };
    }
    return {
      success: false,
      error: {
        message: 'Unknown error',
        status: 0
      }
    };
  }
}
```

## Common Error Scenarios

### Invalid API Key

```typescript theme={null}
try {
  const client = new Orchata({ apiKey: 'invalid_key' });
  await client.spaces.list();
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Please check your API key');
  }
}
```

### Resource Not Found

```typescript theme={null}
try {
  await client.spaces.get('nonexistent_space');
} catch (error) {
  if (error instanceof NotFoundError) {
    console.error('Space does not exist or you do not have access');
  }
}
```

### Validation Errors

```typescript theme={null}
try {
  await client.spaces.create({
    name: '', // Invalid: empty name
    description: 'Test'
  });
} catch (error) {
  if (error instanceof UnprocessableEntityError) {
    console.error('Validation failed:', error.message);
  }
}
```

### Network Issues

```typescript theme={null}
try {
  await client.query({ spaceIds: 'space_123', query: 'test' });
} catch (error) {
  if (error instanceof ConnectionError) {
    console.error('Network error. Check your connection.');
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out. Try again later.');
  }
}
```

## Error Handling Best Practices

<CardGroup cols={2}>
  <Card title="Handle Specific Errors" icon="target">
    Catch specific error types to provide better user feedback and handle each case appropriately.
  </Card>

  <Card title="Retry Rate Limits" icon="refresh-cw">
    Implement retry logic for `RateLimitError` using the `retryAfter` property.
  </Card>

  <Card title="Log Errors" icon="file-text">
    Log errors with context (request details, user ID, etc.) for debugging.
  </Card>

  <Card title="Graceful Degradation" icon="shield">
    Provide fallback behavior when errors occur (e.g., show cached data or default message).
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Usage Guide" icon="book" href="/sdk/usage">
    Learn about Spaces, Documents, and Queries APIs.
  </Card>

  <Card title="AI Integration" icon="sparkles" href="/sdk/ai-integration">
    Integrate with Vercel AI SDK for AI-powered applications.
  </Card>

  <Card title="Quickstart" icon="rocket" href="/sdk/quickstart">
    Review the quickstart guide.
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore the REST API documentation.
  </Card>
</CardGroup>
