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

# Error Handling

> Understanding and handling API errors

This page covers all error responses you may encounter when calling Endprompt endpoints.

## Error Response Format

All errors follow a consistent format:

```json theme={null}
{
  "error": "error_code",
  "message": "Human-readable description",
  "field": "field_name",       // Optional: for validation errors
  "details": {}                 // Optional: additional context
}
```

## HTTP Status Codes

| Code  | Meaning          | When It Occurs                   |
| ----- | ---------------- | -------------------------------- |
| `400` | Bad Request      | Invalid JSON, malformed request  |
| `401` | Unauthorized     | Missing or invalid API key       |
| `403` | Forbidden        | Access denied to resource        |
| `404` | Not Found        | Endpoint or prompt doesn't exist |
| `422` | Validation Error | Input doesn't match schema       |
| `429` | Rate Limited     | Too many requests                |
| `500` | Server Error     | Internal error                   |
| `502` | Bad Gateway      | LLM provider error               |
| `504` | Timeout          | Request took too long            |

## Error Types

### 401 Unauthorized

```json theme={null}
{
  "error": "unauthorized",
  "message": "Invalid or missing API key"
}
```

**Causes:**

* `x-api-key` header is missing
* API key is invalid or malformed
* API key has been revoked

**Solutions:**

```javascript theme={null}
// Ensure header is set correctly
headers: {
  'x-api-key': 'ep_live_xxxxxxxxxxxxxxxxxxxx'  // Not 'Authorization: Bearer ...'
}
```

### 403 Forbidden

```json theme={null}
{
  "error": "forbidden",
  "message": "Access denied to this endpoint"
}
```

**Causes:**

* Endpoint is private/internal
* API key doesn't have permission

### 404 Not Found

```json theme={null}
{
  "error": "not_found",
  "message": "Endpoint '/api/v1/unknown' not found"
}
```

**Causes:**

* Typo in endpoint path
* Endpoint was deleted
* Wrong tenant subdomain

**Solution:** Verify the endpoint exists in your dashboard.

### 422 Validation Error

```json theme={null}
{
  "error": "validation_error",
  "message": "Field 'text' is required",
  "field": "text"
}
```

**Common validation errors:**

| Error            | Message                               | Solution                   |
| ---------------- | ------------------------------------- | -------------------------- |
| Missing field    | "Field 'x' is required"               | Include the required field |
| Wrong type       | "Field 'x' must be a string"          | Check data type            |
| Out of range     | "Field 'x' must be between 1 and 100" | Adjust value               |
| Pattern mismatch | "Field 'x' must match pattern"        | Fix format                 |
| Enum violation   | "Field 'x' must be one of: a, b, c"   | Use allowed value          |

### 429 Rate Limited

```json theme={null}
{
  "error": "rate_limit_exceeded",
  "message": "Rate limit exceeded. Try again in 45 seconds.",
  "retry_after": 45
}
```

**Response Headers:**

```
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1699999999
```

**Handling:**

```javascript theme={null}
async function callWithRetry(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status === 429) {
        const retryAfter = error.retryAfter || 60;
        await sleep(retryAfter * 1000);
        continue;
      }
      throw error;
    }
  }
  throw new Error('Max retries exceeded');
}
```

### 500 Server Error

```json theme={null}
{
  "error": "internal_error",
  "message": "An unexpected error occurred",
  "request_id": "req_xxxxxxxxxxxx"
}
```

**What to do:**

1. Note the `request_id`
2. Retry the request (may be transient)
3. Contact support with the request ID if persistent

### 502 Bad Gateway

```json theme={null}
{
  "error": "provider_error",
  "message": "LLM provider returned an error",
  "details": {
    "provider": "openai",
    "code": "rate_limit_exceeded"
  }
}
```

**Causes:**

* LLM provider (OpenAI, Anthropic) is down
* Provider rate limits exceeded
* Invalid provider API key in settings

### 504 Timeout

```json theme={null}
{
  "error": "timeout",
  "message": "Request timed out after 60 seconds"
}
```

**Causes:**

* Very long input text
* Complex prompt requiring extended processing
* LLM provider slowdown

**Solutions:**

* Reduce input size
* Simplify the prompt
* Increase client timeout setting

## Error Handling Best Practices

### Implement Exponential Backoff

```javascript theme={null}
async function callWithBackoff(fn, maxRetries = 5) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status === 429 || error.status >= 500) {
        const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s, 8s, 16s
        await sleep(delay);
        continue;
      }
      throw error; // Don't retry client errors
    }
  }
  throw new Error('Max retries exceeded');
}
```

### Log Request IDs

```javascript theme={null}
try {
  const response = await fetch(url, options);
  const requestId = response.headers.get('X-Request-Id');
  console.log('Request ID:', requestId);
  
  if (!response.ok) {
    const error = await response.json();
    console.error('Error:', error, 'Request ID:', requestId);
    throw error;
  }
} catch (error) {
  // Include request ID in error reports
}
```

### Handle Specific Errors

```javascript theme={null}
async function handleEndpromptError(error) {
  switch (error.error) {
    case 'validation_error':
      // Show user-friendly validation message
      return `Invalid input: ${error.message}`;
    
    case 'rate_limit_exceeded':
      // Queue for retry
      return 'Service busy, retrying...';
    
    case 'provider_error':
      // Fallback or notify
      return 'AI service temporarily unavailable';
    
    default:
      // Generic error
      return 'Something went wrong. Please try again.';
  }
}
```

## Testing Error Handling

Test your error handling by:

1. **Missing field** — Omit a required field
2. **Invalid type** — Send string instead of number
3. **Invalid key** — Use a fake API key
4. **Rate limit** — Send many rapid requests

## Next Steps

<CardGroup cols={2}>
  <Card title="Logs & Monitoring" icon="chart-line" href="/guides/logs-and-monitoring">
    Debug issues using execution logs
  </Card>

  <Card title="Support" icon="life-ring" href="mailto:support@endprompt.ai">
    Contact support with request IDs
  </Card>
</CardGroup>
