Error Handling

Understand and handle API errors from Wictz API.

Error Handling

Wictz API uses standard HTTP status codes to indicate the success or failure of an API request. Understanding these codes and the accompanying error messages is crucial for building robust applications.

HTTP Status Codes

Here are some common HTTP status codes you might encounter:

Status CodeMeaningCommon Reasons
200 OKRequest successful.The API request was processed successfully by Wictz API and the underlying provider.
400 Bad RequestThe request was unacceptable, often due to missing a required parameter or invalid JSON.Malformed request body, invalid parameters for the chosen model/endpoint.
401 UnauthorizedNo valid API key provided.Missing Authorization header, invalid API key, or expired/revoked key.
403 ForbiddenThe API key doesn't have permissions to perform the request.Key does not have access to the requested model, or the account associated with the key is suspended or has billing issues.
404 Not FoundThe requested resource or endpoint does not exist.Incorrect provider ID or endpoint path in the URL.
429 Too Many RequestsRate limit exceeded, or quota exhausted.Exceeded RPM/TPM limits for your plan/key, or daily/monthly usage quota reached. The response body often contains more details.
500 Internal Server ErrorAn unexpected error occurred on Wictz API's servers.Temporary issue with Wictz API infrastructure. These are rare.
502 Bad Gateway / 503 Service Unavailable / 504 Gateway TimeoutError from the upstream AI provider.The underlying AI provider (e.g., OpenAI, Anthropic) might be experiencing issues, is overloaded, or took too long to respond. Wictz API forwards these errors.

Error Response Format

When an error occurs, Wictz API will return a JSON response containing details about the error. The exact format may vary slightly depending on whether the error originated from Wictz API itself or is being passed through from an underlying provider.

Wictz API Generated Error:

Example Wictz API Error Response (e.g., Rate Limit)
{
  "error": {
    "message": "Rate limit exceeded for model gpt-4. Limit: 10 RPM. Please try again later or upgrade your plan.",
    "type": "rate_limit_exceeded",
    "param": null,
    "code": "rate_limit_exceeded",
    "details": {
      "model": "gpt-4",
      "limit_type": "requests_per_minute",
      "limit_value": 10,
      "current_usage": 11 
    }
  }
}

Provider Error (Passed Through):

If the error originates from the downstream provider (e.g., OpenAI), Wictz API will typically forward the provider's error response directly, along with the original status code.

Example Provider Error (e.g., OpenAI Invalid Request)
{
  "error": {
    "message": "Invalid 'temperature' value: 5.0. Temperature must be between 0 and 2.",
    "type": "invalid_request_error",
    "param": "temperature",
    "code": "invalid_temperature"
  }
}

Always check the response body for specific error messages and codes, as these provide valuable information for debugging.

Common Error Scenarios & Troubleshooting

  • Invalid API Key (401): Ensure your API key is correct, active, and included in the Authorization: Bearer YOUR_API_KEY header.
  • Rate Limit Exceeded (429): Implement exponential backoff in your retry logic. Check your dashboard for current rate limits. Consider upgrading if you consistently hit limits.
  • Model Not Available/Forbidden (403/404): Verify that the model ID is correct and that your current plan grants access to it.
  • Invalid Request Body (400): Double-check that your JSON payload is correctly formatted and includes all required parameters for the specific model and endpoint, according to the provider's documentation.
  • Provider Errors (5xx): These errors usually indicate issues with the AI provider itself. Implement robust retry logic with exponential backoff. If persistent, check the provider's status page.

Retry Logic

It is highly recommended to implement retry logic with exponential backoff for transient errors such as rate limits (429) or temporary server issues (5xx).

JavaScript Example: Fetch with Exponential Backoff
async function makeRequestWithRetry(url, options, maxRetries = 5) {
  let attempt = 0;
  while (attempt < maxRetries) {
    try {
      const response = await fetch(url, options);
      
      if (response.ok) {
        return await response.json();
      }
      
      // Retry on 429, 500, 502, 503, 504
      if ([429, 500, 502, 503, 504].includes(response.status)) {
        attempt++;
        if (attempt >= maxRetries) {
          // Max retries reached, throw error from last attempt
          const errorBody = await response.text();
          throw new Error(`HTTP ${response.status} after ${maxRetries} attempts: ${errorBody}`);
        }
        // Calculate wait time: 2^attempt * 1000ms (e.g., 1s, 2s, 4s, ...) + random jitter
        const waitTime = Math.pow(2, attempt -1) * 1000 + Math.random() * 1000;
        console.log(`Attempt ${attempt} failed with status ${response.status}. Retrying in ${(waitTime / 1000).toFixed(2)}s...`);
        await new Promise(resolve => setTimeout(resolve, waitTime));
        continue;
      }
      
      // For other client errors (4xx not listed above), don't retry, throw immediately
      const errorBody = await response.text();
      throw new Error(`HTTP ${response.status}: ${errorBody}`);
      
    } catch (networkError) { // Catches fetch-specific errors like network down
      attempt++;
      if (attempt >= maxRetries) throw networkError; // Max retries for network errors
      const waitTime = Math.pow(2, attempt-1) * 1000 + Math.random() * 1000;
      console.log(`Network error on attempt ${attempt}. Retrying in ${(waitTime / 1000).toFixed(2)}s...`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    }
  }
}

Adjust maxRetries and the backoff strategy according to your application's needs.