HTTP Status Codes

The StealthGPT API uses standard HTTP status codes to indicate the success or failure of requests:

200 OK
success

The request was successful and the response contains the expected data.

400 Bad Request
error

The request was malformed or contained invalid parameters.

401 Unauthorized
error

Authentication failed, usually due to an invalid or missing API token.

402 Payment Required
error

You don’t have enough credits in your account to perform this action.

403 Forbidden
error

The requested operation could not be completed (e.g., result not available).

429 Too Many Requests
error

You’ve exceeded the rate limits for the API.

500 Internal Server Error
error

An error occurred on the server. These are typically temporary.

Error Response Format

All error responses follow this consistent format:

{
  "message": "Human-readable error message"
}

Some error responses may include additional information:

{
  "message": "Invalid request",
  "info": [
    {
      "code": "invalid_type",
      "expected": "boolean",
      "received": "string",
      "path": ["rephrase"],
      "message": "Expected boolean, received string"
    }
  ]
}

Common Errors and Solutions

Authentication Errors

Request Errors

Rate Limit Errors

Network and Server Errors

Language-Specific Error Handling Examples

Here are comprehensive error handling examples in different programming languages:

import requests
from requests.exceptions import RequestException
import time

class StealthGPTError(Exception):
    """Custom exception for StealthGPT API errors"""
    pass

def call_stealthgpt_api(prompt, rephrase, max_retries=3):
    headers = {
        'api-token': 'YOUR_API_TOKEN',
        'Content-Type': 'application/json'
    }
    data = {
        'prompt': prompt,
        'rephrase': rephrase
    }

    for attempt in range(max_retries):
        try:
            response = requests.post(
                'https://stealthgpt.ai/api/stealthify',
                headers=headers,
                json=data,
                timeout=10
            )
            
            if response.status_code == 200:
                return response.json()
            
            error_data = response.json()
            error_message = error_data.get('message', 'Unknown error')
                
            if response.status_code == 429:
                retry_after = int(response.headers.get('Retry-After', 5))
                time.sleep(retry_after)
                continue
                
            if response.status_code == 400:
                raise StealthGPTError(f"Invalid request: {error_message}")
                
            if response.status_code == 401:
                raise StealthGPTError("Unauthorized: Invalid API token")
            
            if response.status_code == 402:
                raise StealthGPTError("Not enough credits")
                
            response.raise_for_status()
            
        except requests.exceptions.Timeout:
            if attempt == max_retries - 1:
                raise StealthGPTError("Request timed out after multiple attempts")
            time.sleep(2 ** attempt)  # Exponential backoff
            
        except requests.exceptions.RequestException as e:
            raise StealthGPTError(f"Request failed: {str(e)}")
            
    raise StealthGPTError("Max retries exceeded")

Best Practices for Error Handling

  1. Implement Retry Logic: For transient errors (like 429 or 500), implement retry logic with exponential backoff.

  2. Validate Inputs: Validate all parameters before sending requests to avoid 400 errors.

  3. Check Response Status: Always check the HTTP status code before trying to process the response.

  4. Error Logging: Log detailed error information for troubleshooting.

  5. Handle Errors Gracefully: Provide user-friendly error messages in your application rather than exposing raw API errors.

// Node.js example of comprehensive error handling
async function callStealthGPT(prompt, rephrase) {
  try {
    const response = await axios.post('https://stealthgpt.ai/api/stealthify', {
      prompt,
      rephrase
    }, {
      headers: {
        'api-token': process.env.API_TOKEN,
        'Content-Type': 'application/json'
      }
    });
    
    return response.data;
  } catch (error) {
    // Handle different error types
    if (error.response) {
      // The request was made and server responded with an error code
      const errorMessage = error.response.data.message || 'Unknown error';
      
      switch (error.response.status) {
        case 400:
          console.error('Invalid request parameters:', error.response.data);
          throw new Error(`Invalid request: ${errorMessage}`);
        case 401:
          console.error('Authentication failed');
          throw new Error('API authentication failed. Please check your API token.');
        case 402:
          console.error('Payment required');
          throw new Error('Not enough credits to process this request.');
        case 403:
          console.error('Forbidden');
          throw new Error(`Operation not allowed: ${errorMessage}`);
        case 429:
          console.error('Rate limit exceeded');
          throw new Error('Too many requests. Please try again later.');
        default:
          console.error(`Error ${error.response.status}:`, error.response.data);
          throw new Error('An error occurred while processing your request.');
      }
    } else if (error.request) {
      // The request was made but no response received
      console.error('No response received:', error.request);
      throw new Error('No response from server. Please check your connection.');
    } else {
      // Something else caused the error
      console.error('Error setting up request:', error.message);
      throw new Error('Failed to send request.');
    }
  }
}