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

# Error Handling

> Understand and handle API errors

# Error Handling

The Tokencraft API uses conventional HTTP status codes to indicate success or failure of requests. All error responses include a JSON body with an `error` field describing the problem.

## Error Response Format

```json theme={null}
{
  "error": "Error message describing what went wrong"
}
```

## Status Codes

### 2xx Success

| Code  | Description                             |
| ----- | --------------------------------------- |
| `200` | OK - Request succeeded                  |
| `201` | Created - Resource created successfully |

### 4xx Client Errors

| Code  | Description                                         |
| ----- | --------------------------------------------------- |
| `400` | Bad Request - Invalid input or parameters           |
| `401` | Unauthorized - Missing or invalid authentication    |
| `403` | Forbidden - Valid auth but insufficient permissions |
| `404` | Not Found - Resource doesn't exist                  |
| `429` | Too Many Requests - Rate limit exceeded             |

### 5xx Server Errors

| Code  | Description                                             |
| ----- | ------------------------------------------------------- |
| `500` | Internal Server Error - Something went wrong on our end |
| `503` | Service Unavailable - Temporary outage                  |

## Common Errors

### 401 Unauthorized

**Cause:** Missing or invalid API token

```json theme={null}
{
  "error": "Invalid API token"
}
```

**Solutions:**

* Verify your token is correct
* Check the Authorization header format: `Bearer tkc_xxx`
* Ensure the token hasn't been revoked
* Generate a new token if necessary

**Example:**

```bash theme={null}
# ❌ Wrong
curl https://app.tokencraft.dev/api/v1/workspaces

# ✅ Correct
curl -H "Authorization: Bearer tkc_your_token" \
  https://app.tokencraft.dev/api/v1/workspaces
```

### 404 Not Found

**Cause:** Resource doesn't exist or you don't have access

```json theme={null}
{
  "error": "Workspace not found"
}
```

```json theme={null}
{
  "error": "Tokenset not found"
}
```

**Solutions:**

* Verify the resource ID is correct
* Ensure you have access to the resource
* Check for typos in the endpoint URL

### 403 Forbidden

**Cause:** Scope missing or workspace role/plan does not allow the operation

```json theme={null}
{
  "error": "This operation requires the 'write:tokens' scope"
}
```

```json theme={null}
{
  "error": "Your workspace role does not allow API write operations on this TEAM workspace."
}
```

```json theme={null}
{
  "error": "API write access is not available for this workspace owner's current plan."
}
```

**Solutions:**

* Ensure your token includes the required scope (`write:tokens` or `export:tokens`)
* Verify your workspace role (TEAM viewers cannot write)
* Verify the workspace owner plan allows API write access

### 410 Gone (Deprecated Session Endpoint)

**Cause:** Legacy workspace invitation link endpoints are deprecated

```json theme={null}
{
  "error": "Workspace invitation links are deprecated. Members are now added instantly from workspace settings."
}
```

**Affected endpoints:**

* `POST /api/workspaces/invitations/accept`
* `GET /api/workspaces/invitations/verify`
* `DELETE /api/workspaces/invitations/{id}`

### 400 Bad Request

**Cause:** Invalid input data

```json theme={null}
{
  "error": "Name is required"
}
```

```json theme={null}
{
  "error": "Invalid token type"
}
```

**Solutions:**

* Check required fields are provided
* Validate input format matches API expectations
* Review the endpoint documentation

**Example:**

```bash theme={null}
# ❌ Wrong - missing required field
curl -X POST https://app.tokencraft.dev/api/v1/workspaces \
  -H "Authorization: Bearer tkc_token" \
  -H "Content-Type: application/json" \
  -d '{}'

# ✅ Correct
curl -X POST https://app.tokencraft.dev/api/v1/workspaces \
  -H "Authorization: Bearer tkc_token" \
  -H "Content-Type: application/json" \
  -d '{"name":"My Workspace"}'
```

### 429 Rate Limit Exceeded

**Cause:** Too many requests in a short time

```json theme={null}
{
  "error": "Rate limit exceeded. Please try again later."
}
```

**Solutions:**

* Wait 60 seconds before retrying
* Implement exponential backoff
* Reduce request frequency
* Cache API responses

See [Rate Limits](/api-reference/rate-limits) for details.

### 500 Internal Server Error

**Cause:** Server-side error

```json theme={null}
{
  "error": "Internal server error"
}
```

**Solutions:**

* Retry the request after a short delay
* Check [status page](https://status.tokencraft.dev) for outages
* Contact support if the issue persists

## Error Handling Examples

### JavaScript/TypeScript

```javascript theme={null}
async function fetchWorkspaces(token) {
  try {
    const response = await fetch('https://app.tokencraft.dev/api/v1/workspaces', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    if (!response.ok) {
      const error = await response.json();
      
      switch (response.status) {
        case 401:
          throw new Error('Authentication failed. Check your API token.');
        case 404:
          throw new Error('Resource not found.');
        case 429:
          throw new Error('Rate limit exceeded. Please wait and try again.');
        case 500:
          throw new Error('Server error. Please try again later.');
        default:
          throw new Error(error.error || 'An error occurred');
      }
    }

    return await response.json();
  } catch (error) {
    console.error('API Error:', error.message);
    throw error;
  }
}
```

### Python

```python theme={null}
import requests
from time import sleep

def fetch_workspaces(token):
    headers = {'Authorization': f'Bearer {token}'}
    
    try:
        response = requests.get(
            'https://app.tokencraft.dev/api/v1/workspaces',
            headers=headers
        )
        
        response.raise_for_status()
        return response.json()
        
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            raise Exception('Authentication failed. Check your API token.')
        elif e.response.status_code == 404:
            raise Exception('Resource not found.')
        elif e.response.status_code == 429:
            raise Exception('Rate limit exceeded. Please wait and try again.')
        elif e.response.status_code == 500:
            raise Exception('Server error. Please try again later.')
        else:
            error_data = e.response.json()
            raise Exception(error_data.get('error', 'An error occurred'))
    
    except requests.exceptions.RequestException as e:
        raise Exception(f'Network error: {str(e)}')
```

### With Retry Logic

```javascript theme={null}
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);

      // Don't retry client errors (except 429)
      if (response.status >= 400 && response.status < 500 && response.status !== 429) {
        const error = await response.json();
        throw new Error(error.error || 'Client error');
      }

      // Retry on rate limit or server error
      if (response.status === 429 || response.status >= 500) {
        const waitTime = Math.pow(2, attempt) * 1000; // Exponential backoff
        console.log(`Attempt ${attempt + 1} failed. Retrying in ${waitTime}ms...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || 'Request failed');
      }

      return await response.json();

    } catch (error) {
      if (attempt === maxRetries - 1) {
        throw error;
      }
    }
  }

  throw new Error('Max retries exceeded');
}

// Usage
try {
  const data = await fetchWithRetry(
    'https://app.tokencraft.dev/api/v1/workspaces',
    {
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );
  console.log(data);
} catch (error) {
  console.error('Failed to fetch workspaces:', error.message);
}
```

## Validation Errors

When creating or updating resources, validation errors provide specific field information:

```json theme={null}
{
  "error": "Name is required"
}
```

```json theme={null}
{
  "error": "Invalid token type. Supported types: color, dimension, fontFamily, fontWeight, fontSize, lineHeight, letterSpacing, duration, cubicBezier, number, strokeStyle, border, transition, shadow, gradient, typography"
}
```

## Best Practices

### 1. Always Check Response Status

```javascript theme={null}
if (!response.ok) {
  const error = await response.json();
  throw new Error(error.error);
}
```

### 2. Implement Retry Logic

For rate limits and server errors:

```javascript theme={null}
const maxRetries = 3;
const backoff = [1000, 2000, 4000]; // ms

for (let i = 0; i < maxRetries; i++) {
  try {
    return await makeRequest();
  } catch (error) {
    if (i === maxRetries - 1) throw error;
    await sleep(backoff[i]);
  }
}
```

### 3. Log Errors Appropriately

```javascript theme={null}
console.error('API Error:', {
  status: response.status,
  error: errorData.error,
  endpoint: url,
  timestamp: new Date().toISOString()
});
```

### 4. Provide User-Friendly Messages

```javascript theme={null}
function getUserMessage(statusCode, error) {
  const messages = {
    401: 'Please check your API credentials and try again.',
    404: 'The requested resource was not found.',
    429: 'Too many requests. Please wait a moment and try again.',
    500: 'Something went wrong. Please try again later.'
  };
  
  return messages[statusCode] || error || 'An unexpected error occurred.';
}
```

## Debugging Tips

### 1. Use Verbose Logging

```bash theme={null}
curl -v -H "Authorization: Bearer tkc_token" \
  https://app.tokencraft.dev/api/v1/workspaces
```

### 2. Check Request Format

Ensure:

* Authorization header is present and correct
* Content-Type header is set for POST/PATCH
* Request body is valid JSON
* URL is properly formatted

### 3. Validate Token

Test your token with a simple request:

```bash theme={null}
curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://app.tokencraft.dev/api/v1/workspaces
```

### 4. Check Rate Limit Headers

Response headers include rate limit info:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1633024800
```

## Getting Help

If you encounter persistent errors:

1. Check the [documentation](/api-reference/introduction)
2. Review your request format and authentication
3. Check for service status updates
4. Contact support with:
   * Request details (endpoint, method, headers)
   * Response status and error message
   * Timestamp of the request
   * Your API token ID (not the full token)

## Next Steps

<CardGroup cols={2}>
  <Card title="Rate Limits" icon="gauge" href="/api-reference/rate-limits">
    Understand rate limiting
  </Card>

  <Card title="Authentication" icon="key" href="/authentication">
    Learn about API authentication
  </Card>
</CardGroup>
