Error Handling

Understanding and handling API errors effectively

Error Response Format

When an error occurs, the Omni API returns an appropriate HTTP status code and a JSON response with details about the error. The error response has the following format:

{
  "error": {
    "code": "error_code",
    "message": "Detailed error message"
  }
}

HTTP Status Codes

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

Status CodeDescription
200 OKThe request was successful
400 Bad RequestThe request was invalid or malformed
401 UnauthorizedAuthentication is required (missing API key)
403 ForbiddenThe API key is invalid or doesn't have permission to access the requested resource
404 Not FoundThe requested resource doesn't exist
429 Too Many RequestsRate limit exceeded
500 Internal Server ErrorAn error occurred on the server

Common Error Codes

The code field in the error response provides a machine-readable identifier for the error. Here are some common error codes:

Error CodeDescription
missing_api_keyThe API key is missing from the request
invalid_api_keyThe API key is invalid or has been revoked
rate_limit_exceededThe rate limit for the API key has been exceeded
invalid_requestThe request is invalid or malformed
invalid_inputThe input data is invalid or missing required fields
content_limit_exceededThe content exceeds the maximum allowed size
server_errorAn error occurred on the server

Error Examples

Missing API Key

{
  "error": {
    "code": "missing_api_key",
    "message": "API key is required. Please include an X-API-Key header."
  }
}

Invalid API Key

{
  "error": {
    "code": "invalid_api_key",
    "message": "The provided API key is invalid or has been revoked."
  }
}

Rate Limit Exceeded

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please try again later."
  }
}

Invalid Request

{
  "error": {
    "code": "invalid_request",
    "message": "The request body is not valid JSON."
  }
}

Invalid Input

{
  "error": {
    "code": "invalid_input",
    "message": "The 'input' field is required and must be an array."
  }
}

Content Limit Exceeded

{
  "error": {
    "code": "content_limit_exceeded",
    "message": "The text content exceeds the maximum allowed length of 10,000 characters."
  }
}

Handling Errors in Your Code

Here are some examples of how to handle errors in your code:

JavaScript

async function moderateContent(apiKey, input) {
  try {
    const response = await fetch('https://api.omnimoderate.com/v1/moderate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': apiKey
      },
      body: JSON.stringify({ input })
    });
    
    // Parse the response as JSON
    const data = await response.json();
    
    // Check if the response is an error
    if (!response.ok) {
      // Handle the error based on the status code and error code
      switch (response.status) {
        case 400:
          console.error('Bad Request:', data.error.message);
          // Handle invalid request
          break;
        case 401:
          console.error('Unauthorized:', data.error.message);
          // Handle missing API key
          break;
        case 403:
          console.error('Forbidden:', data.error.message);
          // Handle invalid API key
          break;
        case 429:
          console.error('Rate Limit Exceeded:', data.error.message);
          // Implement retry logic with exponential backoff
          break;
        case 500:
          console.error('Server Error:', data.error.message);
          // Handle server error
          break;
        default:
          console.error('Error:', data.error.message);
          // Handle other errors
      }
      
      throw new Error(data.error.message);
    }
    
    // Return the successful response
    return data;
  } catch (error) {
    // Handle network errors or other exceptions
    console.error('Error moderating content:', error.message);
    throw error;
  }
}

Python

import requests

def moderate_content(api_key, input_data):
    try:
        response = requests.post(
            'https://api.omnimoderate.com/v1/moderate',
            headers={
                'Content-Type': 'application/json',
                'X-API-Key': api_key
            },
            json={'input': input_data}
        )
        
        # Parse the response as JSON
        data = response.json()
        
        # Check if the response is an error
        if response.status_code != 200:
            # Handle the error based on the status code and error code
            if response.status_code == 400:
                print(f"Bad Request: {data['error']['message']}")
                # Handle invalid request
            elif response.status_code == 401:
                print(f"Unauthorized: {data['error']['message']}")
                # Handle missing API key
            elif response.status_code == 403:
                print(f"Forbidden: {data['error']['message']}")
                # Handle invalid API key
            elif response.status_code == 429:
                print(f"Rate Limit Exceeded: {data['error']['message']}")
                # Implement retry logic with exponential backoff
            elif response.status_code == 500:
                print(f"Server Error: {data['error']['message']}")
                # Handle server error
            else:
                print(f"Error: {data['error']['message']}")
                # Handle other errors
            
            raise Exception(data['error']['message'])
        
        # Return the successful response
        return data
    except requests.exceptions.RequestException as e:
        # Handle network errors or other exceptions
        print(f"Error moderating content: {str(e)}")
        raise

Best Practices

  • Always check for errors - Don't assume that API requests will always succeed
  • Handle different error types appropriately - Different errors may require different handling strategies
  • Implement retry logic for rate limiting - When you receive a rate limit error, wait before retrying the request
  • Log errors for debugging - Keep track of errors to help identify and fix issues
  • Provide meaningful error messages to users - Translate API errors into user-friendly messages

Next Steps