Skip to main content

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

{
  "error": "Error message describing what went wrong"
}

Status Codes

2xx Success

CodeDescription
200OK - Request succeeded
201Created - Resource created successfully

4xx Client Errors

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

5xx Server Errors

CodeDescription
500Internal Server Error - Something went wrong on our end
503Service Unavailable - Temporary outage

Common Errors

401 Unauthorized

Cause: Missing or invalid API token
{
  "error": "Invalid API token"
}
Solutions:
  • Verify your token is correct
  • Check the Authorization header format: Bearer dtk_xxx
  • Ensure the token hasn’t been revoked
  • Generate a new token if necessary
Example:
# ❌ Wrong
curl https://app.tokencraft.dev/api/v1/workspaces

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

404 Not Found

Cause: Resource doesn’t exist or you don’t have access
{
  "error": "Workspace not found"
}
{
  "error": "Tokenset not found"
}
Solutions:
  • Verify the resource ID is correct
  • Ensure you own the resource
  • Check for typos in the endpoint URL

400 Bad Request

Cause: Invalid input data
{
  "error": "Name is required"
}
{
  "error": "Invalid token type"
}
Solutions:
  • Check required fields are provided
  • Validate input format matches API expectations
  • Review the endpoint documentation
Example:
# ❌ Wrong - missing required field
curl -X POST https://app.tokencraft.dev/api/v1/workspaces \
  -H "Authorization: Bearer dtk_token" \
  -H "Content-Type: application/json" \
  -d '{}'

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

429 Rate Limit Exceeded

Cause: Too many requests in a short time
{
  "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 for details.

500 Internal Server Error

Cause: Server-side error
{
  "error": "Internal server error"
}
Solutions:
  • Retry the request after a short delay
  • Check status page for outages
  • Contact support if the issue persists

Error Handling Examples

JavaScript/TypeScript

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

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

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:
{
  "error": "Name is required"
}
{
  "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

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

2. Implement Retry Logic

For rate limits and server errors:
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

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

4. Provide User-Friendly Messages

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

curl -v -H "Authorization: Bearer dtk_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:
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
  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