Skip to content

Error Handling

This page provides information about error handling in the Bluefly LLM ecosystem API.

Error Response Format

All API errors are returned with appropriate HTTP status codes and a consistent JSON response format:

{
  "error": {
    "code": "error_code",
    "message": "Human-readable error message",
    "details": "Additional details about the error",
    "request_id": "unique-request-identifier"
  }
}

The error response includes the following fields:

  • code: A machine-readable error code
  • message: A human-readable description of the error
  • details: Additional information about the error (optional)
  • request_id: A unique identifier for the request, useful for troubleshooting with support

HTTP Status Codes

The API uses standard HTTP status codes to indicate the success or failure of a request:

Status Code Description
200 OK The request was successful
400 Bad Request The request was invalid or could not be processed
401 Unauthorized Authentication failed
403 Forbidden The authenticated user does not have access to the requested resource
404 Not Found The requested resource was not found
409 Conflict The request could not be completed due to a conflict with the current state of the resource
422 Unprocessable Entity The request was well-formed but could not be processed due to semantic errors
429 Too Many Requests The client has sent too many requests in a given time period
500 Internal Server Error An error occurred on the server
503 Service Unavailable The server is currently unable to handle the request

Common Error Codes

Authentication Errors

Error Code Description Status Code
authentication_required Authentication is required to access this resource 401
invalid_api_key The API key provided is invalid 401
invalid_token The authentication token is invalid 401
token_expired The authentication token has expired 401

Authorization Errors

Error Code Description Status Code
permission_denied The authenticated user does not have permission to access this resource 403
insufficient_scope The request requires higher privileges than provided by the token 403
resource_forbidden The authenticated user is forbidden from accessing this resource 403

Request Validation Errors

Error Code Description Status Code
invalid_request The request is invalid 400
missing_parameter A required parameter is missing 400
invalid_parameter A parameter has an invalid value 400
unsupported_parameter A parameter was provided that is not supported 400
invalid_content_type The content type of the request is invalid 400

Resource Errors

Error Code Description Status Code
resource_not_found The requested resource was not found 404
model_not_found The requested model was not found 404
resource_conflict The request conflicts with the current state of the resource 409
resource_exists The resource already exists 409

Rate Limiting Errors

Error Code Description Status Code
rate_limit_exceeded You have exceeded your rate limit 429
quota_exceeded You have exceeded your quota for this resource 429

Server Errors

Error Code Description Status Code
server_error An error occurred on the server 500
service_unavailable The service is currently unavailable 503
model_overloaded The model is currently overloaded 503

Model Errors

Error Code Description Status Code
model_error An error occurred during model execution 500
content_filtered The input or output was filtered by content filters 422
max_tokens_exceeded The input exceeds the maximum number of tokens 400
unsafe_content The request contains content that is unsafe or violates policies 400

Error Handling Examples

JavaScript Example

async function callApi(endpoint, params) {
  try {
    const response = await fetch(`https://api.bluefly.io${endpoint}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify(params)
    });

    const data = await response.json();

    if (!response.ok) {
      // Handle API error
      const error = data.error || { message: 'Unknown error' };

      // Handle specific error codes
      switch (error.code) {
        case 'rate_limit_exceeded':
          console.warn(`Rate limit exceeded. Retry after ${response.headers.get('retry-after')} seconds.`);
          break;
        case 'invalid_api_key':
          console.error('API key is invalid. Please check your configuration.');
          break;
        case 'model_not_found':
          console.error(`Model ${params.model} not found. Please check available models.`);
          break;
        default:
          console.error(`API Error: ${error.message}`, error);
      }

      // Log request ID for troubleshooting
      if (error.request_id) {
        console.error(`Request ID: ${error.request_id}`);
      }

      throw new Error(`API Error: ${error.message}`);
    }

    return data;
  } catch (error) {
    // Handle network errors
    if (error.name === 'FetchError') {
      console.error('Network error:', error.message);
    }

    throw error;
  }
}

Python Example

import requests

def call_api(endpoint, params):
    try:
        response = requests.post(
            f"https://api.bluefly.io{endpoint}",
            json=params,
            headers={
                'Content-Type': 'application/json',
                'Authorization': f"Bearer {API_KEY}"
            }
        )

        # Raise HTTPError for bad responses
        response.raise_for_status()

        return response.json()

    except requests.exceptions.HTTPError as e:
        # Handle API errors
        try:
            error_data = e.response.json().get('error', {})
            error_code = error_data.get('code', 'unknown_error')
            error_message = error_data.get('message', 'Unknown error')
            request_id = error_data.get('request_id')

            # Handle specific error codes
            if error_code == 'rate_limit_exceeded':
                retry_after = e.response.headers.get('retry-after', '60')
                print(f"Rate limit exceeded. Retry after {retry_after} seconds.")
            elif error_code == 'invalid_api_key':
                print("API key is invalid. Please check your configuration.")
            elif error_code == 'model_not_found':
                print(f"Model {params.get('model')} not found. Please check available models.")
            else:
                print(f"API Error: {error_message}")

            # Log request ID for troubleshooting
            if request_id:
                print(f"Request ID: {request_id}")

        except ValueError:
            # Response wasn't valid JSON
            print(f"API Error: {e}")

        raise

    except requests.exceptions.RequestException as e:
        # Handle network errors
        print(f"Network error: {e}")
        raise

Best Practices for Error Handling

1. Implement Proper Error Handling

Always implement proper error handling in your applications to provide a good user experience and make debugging easier.

2. Check Error Codes

Check the error code to handle specific errors differently. For example, rate limit errors might be handled with a retry mechanism, while authentication errors might require the user to log in again.

3. Log Request IDs

Log the request_id from error responses. This ID is crucial when working with support to troubleshoot issues.

4. Implement Retries with Backoff

Implement a retry mechanism with exponential backoff for transient errors like rate limits or server errors:

async function callWithRetry(fn, maxRetries = 3, initialDelay = 1000) {
  let retries = 0;
  while (true) {
    try {
      return await fn();
    } catch (error) {
      // Check if error is retryable
      if (
        retries >= maxRetries ||
        !isRetryableError(error)
      ) {
        throw error;
      }

      // Determine delay with exponential backoff
      const delay = initialDelay * Math.pow(2, retries) + Math.random() * 100;
      console.log(`Retrying after ${delay}ms...`);

      await new Promise(resolve => setTimeout(resolve, delay));
      retries++;
    }
  }
}

function isRetryableError(error) {
  // Determine if the error is retryable
  if (!error.code) return false;

  return [
    'rate_limit_exceeded',
    'server_error',
    'service_unavailable',
    'model_overloaded'
  ].includes(error.code);
}

5. Provide Clear Error Messages to Users

Translate API error messages into user-friendly messages that help them understand what went wrong and how to fix it.

function getUserFriendlyErrorMessage(error) {
  switch (error.code) {
    case 'authentication_required':
      return 'Please log in to continue.';
    case 'permission_denied':
      return 'You do not have permission to access this resource.';
    case 'rate_limit_exceeded':
      return 'You have made too many requests. Please try again later.';
    case 'model_not_found':
      return 'The selected AI model is not available. Please choose another model.';
    case 'content_filtered':
      return 'Your request contains content that is not allowed.';
    case 'max_tokens_exceeded':
      return 'Your input is too long. Please reduce the length and try again.';
    default:
      return 'An error occurred. Please try again later.';
  }
}

Contacting Support

If you encounter persistent errors or need assistance, contact support with the following information:

  1. The request_id from the error response
  2. The error code and message
  3. The request details (endpoint, parameters, etc.)
  4. Any steps to reproduce the error

Contact support at [email protected].