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

# Error Handling

> How to handle API errors

# Error Handling

The Voicy API uses conventional HTTP status codes to indicate success or failure of requests.

## Error Response Format

All error responses follow this format:

```json theme={null}
{
  "error": "Description of what went wrong"
}
```

## HTTP Status Codes

### Success Codes

| Code | Meaning | When Used                                    |
| ---- | ------- | -------------------------------------------- |
| 200  | OK      | Successful GET, POST, PATCH, DELETE requests |
| 201  | Created | Successful resource creation (call-dial)     |

### Client Error Codes

| Code | Meaning              | Common Causes                                                      |
| ---- | -------------------- | ------------------------------------------------------------------ |
| 400  | Bad Request          | Invalid JSON, missing required fields, invalid phone number format |
| 401  | Unauthorized         | Invalid API key, expired token, missing Authorization header       |
| 403  | Forbidden            | API key doesn't have access to the requested resource              |
| 404  | Not Found            | Call ID doesn't exist or belongs to another account                |
| 422  | Unprocessable Entity | Request is valid but cannot be processed                           |
| 429  | Too Many Requests    | Rate limit exceeded                                                |

### Server Error Codes

| Code | Meaning               | What To Do                                                    |
| ---- | --------------------- | ------------------------------------------------------------- |
| 500  | Internal Server Error | Retry with exponential backoff, contact support if persistent |
| 502  | Bad Gateway           | Temporary issue, retry after a few seconds                    |
| 503  | Service Unavailable   | Service is temporarily down, retry later                      |

## Common Errors

### Authentication Errors

```json theme={null}
// Missing Authorization header
{
  "error": "Missing authorization"
}

// Invalid API key
{
  "error": "Invalid API key"
}

// Expired JWT token (dashboard)
{
  "error": "Invalid or expired token"
}
```

### Validation Errors

```json theme={null}
// Invalid phone number format
{
  "error": "Invalid phone number format. Use E.164 (e.g. +11234567890)"
}

// Missing required field
{
  "error": "to_number is required"
}

// Phone number not in your account
{
  "error": "Phone number not found or not assigned to your account"
}
```

### Access Errors

```json theme={null}
// Trying to access another account's data
{
  "error": "Access denied"
}

// Resource doesn't exist
{
  "error": "Call not found"
}
```

## Best Practices

### Retry Logic

Implement exponential backoff for transient errors:

```javascript theme={null}
async function callWithRetry(fn, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status >= 500 && attempt < maxRetries - 1) {
        // Wait 2^attempt seconds before retrying
        await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));
        continue;
      }
      throw error;
    }
  }
}
```

### Error Logging

Log errors with context for debugging:

```javascript theme={null}
try {
  const call = await createPhoneCall(fromNumber, toNumber);
} catch (error) {
  console.error('Failed to create call', {
    fromNumber,
    toNumber,
    status: error.status,
    message: error.message,
  });
  throw error;
}
```

### User-Friendly Messages

Map API errors to user-friendly messages:

```javascript theme={null}
function getUserMessage(error) {
  switch (error.message) {
    case 'Invalid phone number format. Use E.164 (e.g. +11234567890)':
      return 'Please enter a valid phone number with country code (e.g., +1 555 123 4567)';
    case 'Phone number not found or not assigned to your account':
      return 'This phone number is not available. Please contact support.';
    default:
      return 'Something went wrong. Please try again.';
  }
}
```
