Handle API errors gracefully

Error Handling

Learn how to handle errors returned by the API.

Error Format

All errors return a JSON object with an
text
error
field:
json
{
  "error": "Descriptive error message"
}

Error Codes

StatusErrorCause
401Missing API keyNo API key provided
401Invalid API keyWrong or expired key
403Site is inactiveSite disabled or expired
422Invalid requestMalformed request body
429Rate limit exceededToo many requests
429Daily limit exceededDaily quota reached
500AI service errorProvider unavailable

Handling Errors

Example Error Handling

javascript
async function sendMessage(message) {
  try {
    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': API_KEY
      },
      body: JSON.stringify({
        message,
        session_id: SESSION_ID
      })
    });

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

    return await response.json();
  } catch (err) {
    console.error('Error:', err.message);
    // Show user-friendly message
    showNotification('Failed to get response. Please try again.');
  }
}

Retry Strategy

For transient errors (500, 429), implement exponential backoff:
javascript
async function retryRequest(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === maxRetries - 1) throw err;
      await new Promise(r => setTimeout(r, 1000 * Math.pow(2, i)));
    }
  }
}