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

# Error Handling

> Handle errors gracefully in your application

All API errors throw `TraciaError` with a specific error code.

## Basic Error Handling

```typescript theme={null}
import { Tracia, TraciaError, TraciaErrorCode } from 'tracia';

const tracia = new Tracia({ apiKey: process.env.TRACIA_API_KEY });

try {
  const result = await tracia.prompts.run('welcome-email', { name: 'Alice' });
  console.log(result.text);
} catch (error) {
  if (error instanceof TraciaError) {
    console.error(`Error [${error.code}]: ${error.message}`);
  }
}
```

## Error Codes

| Code                       | Description                                          |
| -------------------------- | ---------------------------------------------------- |
| `UNAUTHORIZED`             | Invalid or missing API key                           |
| `NOT_FOUND`                | The requested resource (prompt, etc.) does not exist |
| `CONFLICT`                 | Resource already exists (e.g., duplicate slug)       |
| `MISSING_VARIABLES`        | Required template variables are missing              |
| `MISSING_PROVIDER_KEY`     | No LLM provider key configured (for `prompts.run()`) |
| `MISSING_PROVIDER_SDK`     | Provider SDK not installed (for `runLocal()`)        |
| `MISSING_PROVIDER_API_KEY` | No provider API key provided (for `runLocal()`)      |
| `UNSUPPORTED_MODEL`        | Model not recognized, use `provider` override        |
| `PROVIDER_ERROR`           | Error from the LLM provider (OpenAI, etc.)           |
| `INVALID_REQUEST`          | Invalid request format                               |
| `NETWORK_ERROR`            | Network connectivity error                           |
| `TIMEOUT`                  | Request timed out (30 second limit)                  |

## Handling Specific Errors

```typescript theme={null}
import { Tracia, TraciaError, TraciaErrorCode } from 'tracia';

const tracia = new Tracia({ apiKey: process.env.TRACIA_API_KEY });

try {
  const result = await tracia.prompts.run('welcome-email', { name: 'Alice' });
  console.log(result.text);
} catch (error) {
  if (error instanceof TraciaError) {
    switch (error.code) {
      case TraciaErrorCode.UNAUTHORIZED:
        console.error('Invalid API key');
        break;
      case TraciaErrorCode.NOT_FOUND:
        console.error('Prompt does not exist');
        break;
      case TraciaErrorCode.CONFLICT:
        console.error('Resource already exists');
        break;
      case TraciaErrorCode.MISSING_VARIABLES:
        console.error('Missing required template variables');
        break;
      case TraciaErrorCode.MISSING_PROVIDER_KEY:
        console.error('No LLM provider configured');
        break;
      case TraciaErrorCode.PROVIDER_ERROR:
        console.error('LLM provider error:', error.message);
        break;
      case TraciaErrorCode.NETWORK_ERROR:
        console.error('Network error:', error.message);
        break;
      case TraciaErrorCode.TIMEOUT:
        console.error('Request timed out');
        break;
      case TraciaErrorCode.MISSING_PROVIDER_SDK:
        console.error('Provider SDK not installed');
        break;
      case TraciaErrorCode.MISSING_PROVIDER_API_KEY:
        console.error('Provider API key not set');
        break;
      case TraciaErrorCode.UNSUPPORTED_MODEL:
        console.error('Model not recognized');
        break;
      default:
        console.error('Unknown error:', error.message);
    }
  }
}
```

## Common Error Scenarios

### Missing Variables

When running a prompt that requires variables you didn't provide:

```typescript theme={null}
// Prompt expects {{name}} and {{product}}
const result = await tracia.prompts.run('welcome-email', {
  name: 'Alice'
  // Missing 'product' variable
});
// Throws TraciaError with code MISSING_VARIABLES
```

### Provider Not Configured

When no LLM provider API key is configured:

```typescript theme={null}
const result = await tracia.prompts.run('welcome-email', { name: 'Alice' });
// Throws TraciaError with code MISSING_PROVIDER_KEY
// Message: "No OpenAI API key configured. Add one in Settings > Providers."
```

### Prompt Not Found

When requesting a prompt that doesn't exist:

```typescript theme={null}
const prompt = await tracia.prompts.get('nonexistent-prompt');
// Throws TraciaError with code NOT_FOUND
```

## runLocal() Errors

The `runLocal()` method has additional error codes specific to local execution.

### Missing Provider SDK

When the required provider SDK is not installed:

```typescript theme={null}
const result = await tracia.runLocal({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }]
});
// Throws TraciaError with code MISSING_PROVIDER_SDK
// Message: "Provider SDK for openai is not installed. Please install the required SDK."
```

**Solution:** Install the provider SDK:

```bash theme={null}
npm install ai @ai-sdk/openai          # For OpenAI models
npm install ai @ai-sdk/anthropic       # For Anthropic models
npm install ai @ai-sdk/google          # For Google models
npm install ai @ai-sdk/amazon-bedrock  # For Amazon Bedrock models
```

### Missing Provider API Key

When no API key is found for the provider:

```typescript theme={null}
const result = await tracia.runLocal({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }]
});
// Throws TraciaError with code MISSING_PROVIDER_API_KEY
// Message: "Missing API key for openai. Set the OPENAI_API_KEY environment variable or provide providerApiKey in options."
```

**Solution:** Set the environment variable or provide `providerApiKey`:

```typescript theme={null}
// Option 1: Environment variable
// OPENAI_API_KEY=sk-your-key

// Option 2: Explicit key
const result = await tracia.runLocal({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }],
  providerApiKey: 'sk-your-key'
});
```

### Unsupported Model

When using a custom model without specifying the provider:

```typescript theme={null}
const result = await tracia.runLocal({
  model: 'my-fine-tuned-model',
  messages: [{ role: 'user', content: 'Hello!' }]
});
// Throws TraciaError with code UNSUPPORTED_MODEL
```

**Solution:** Specify the provider explicitly:

```typescript theme={null}
const result = await tracia.runLocal({
  model: 'my-fine-tuned-model',
  provider: 'openai',
  messages: [{ role: 'user', content: 'Hello!' }]
});
```

## Retry Logic

For transient errors like network issues or rate limits, implement retry logic:

```typescript theme={null}
async function runWithRetry(
  slug: string,
  variables: Record<string, string>,
  maxRetries = 3
) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await tracia.prompts.run(slug, variables);
    } catch (error) {
      if (error instanceof TraciaError) {
        // Don't retry client errors
        if ([
          TraciaErrorCode.UNAUTHORIZED,
          TraciaErrorCode.NOT_FOUND,
          TraciaErrorCode.MISSING_VARIABLES,
          TraciaErrorCode.INVALID_REQUEST,
        ].includes(error.code)) {
          throw error;
        }

        // Retry on transient errors
        if (attempt < maxRetries) {
          const delay = Math.pow(2, attempt) * 1000;
          await new Promise(resolve => setTimeout(resolve, delay));
          continue;
        }
      }
      throw error;
    }
  }
}
```
