Error Handling

Understand and handle API errors gracefully

Error response format

JSON
{
  "success": false,
  "error": "Invalid API key",
  "code": "INVALID_API_KEY",
  "type": "authentication_error",
  "meta": {
    "timestamp": "2026-06-01T10:30:00Z",
    "requestId": "req_abc123def456"
  }
}

Common error codes

401
INVALID_API_KEY
API key is missing, malformed, or invalid
429
RATE_LIMIT_EXCEEDED
Too many requests — see the Plan Limits page
402
INSUFFICIENT_CREDITS
Account has run out of credits
503
MODEL_NOT_AVAILABLE
Requested model is temporarily unavailable
400
INVALID_REQUEST
Request body is malformed or missing required fields
400
CONTEXT_LENGTH_EXCEEDED
Message exceeds the model context window
404
CONVERSATION_NOT_FOUND
RAG conversation ID does not exist
500
INTERNAL_ERROR
Internal server error — please retry

Error handling example

JS
async function handleTarqaRequest(apiKey, requestData) {
  try {
    const response = await fetch(`${BASE_URL}/v1/chat/completions`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    });

    const data = await response.json();

    if (!response.ok || !data.success) {
      const error = data.error || 'Unknown error';
      const code = data.code || 'UNKNOWN_ERROR';

      switch (code) {
        case 'RATE_LIMIT_EXCEEDED':
          const retryAfter = response.headers.get('Retry-After') || 60;
          await new Promise(r => setTimeout(r, retryAfter * 1000));
          return handleTarqaRequest(apiKey, requestData);

        case 'INVALID_API_KEY':
          throw new Error('Authentication failed. Please check your API key.');

        case 'INSUFFICIENT_CREDITS':
          throw new Error('Account out of credits. Please upgrade your plan.');

        case 'CONTEXT_LENGTH_EXCEEDED':
          requestData.messages = truncateMessages(requestData.messages);
          return handleTarqaRequest(apiKey, requestData);

        case 'INTERNAL_ERROR':
          await new Promise(r => setTimeout(r, 5000));
          return handleTarqaRequest(apiKey, requestData);

        default:
          throw new Error(`API Error: ${error} (Code: ${code})`);
      }
    }

    return data;
  } catch (error) {
    console.error('Request failed:', error);
    throw error;
  }
}

// Usage
try {
  const result = await handleTarqaRequest('sk-your-api-key', {
    model: 'gemini-2.5-flash',
    messages: [{ role: 'user', content: 'Hello!' }]
  });
  console.log(result.choices[0].message.content);
} catch (error) {
  showErrorNotification(error.message);
}
Debugging tips

Always log the requestId for support · check response status codes first · validate request format before sending · monitor error rates in analytics

Production best practices

Implement comprehensive error handling · use retry logic with exponential backoff · set up error monitoring · give users friendly error messages