Docs

Error Handling

Learn how to handle errors gracefully and implement robust error handling in your integration.

HTTP Status Codes

The Zyhap API uses standard HTTP status codes to indicate the success or failure of requests.

✅ Success Codes

200OK

Request successful, data returned

201Created

Resource created successfully

204No Content

Request successful, no data returned

❌ Error Codes

400Bad Request

Invalid request data or parameters

401Unauthorized

Invalid or missing API key

403Forbidden

Insufficient permissions, or the module is not available in the country of the branch the key acts in (code ##MODULE_NOT_IN_COUNTRY).

404Not Found

Resource not found

429Too Many Requests

Rate limit exceeded

500Internal Server Error

Server error, try again later

Error Response Format

All API errors follow a consistent format to help you understand and handle them programmatically.

Standard Error Response

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request data",
    "details": [
      {
        "field": "platforms",
        "message": "At least one platform is required"
      },
      {
        "field": "content.text",
        "message": "Content text cannot be empty"
      }
    ],
    "timestamp": "2024-01-01T12:00:00Z",
    "requestId": "req_123456789"
  }
}

Error Fields Explained

FieldTypeDescription
successbooleanAlways false for error responses
error.codestringMachine-readable error code
error.messagestringHuman-readable error description
error.detailsarrayDetailed validation errors (when applicable)
error.requestIdstringUnique identifier for debugging

Common Error Codes

Understanding these error codes will help you handle specific scenarios in your application.

Authentication Errors

INVALID_API_KEY

The provided API key is invalid or expired

MISSING_WORKSPACE_ID

X-Workspace-ID header is required

INSUFFICIENT_PERMISSIONS

API key lacks required permissions

Validation Errors

VALIDATION_ERROR

Request data validation failed

INVALID_DATE_FORMAT

Date must be in ISO 8601 format

CONTENT_TOO_LONG

Content exceeds platform limits

Platform Errors

ACCOUNT_NOT_CONNECTED

Social account not linked to workspace

PLATFORM_ACCESS_REVOKED

Access to platform has been revoked

INVALID_MEDIA_FORMAT

Media format not supported by platform

Rate Limiting

RATE_LIMIT_EXCEEDED

Too many requests, retry after specified time

QUOTA_EXCEEDED

Monthly posting quota exceeded

Implementation Examples

Here are practical examples of how to handle errors in different programming languages.

JavaScript/Node.js

async function createPost(postData) {
  try {
    const response = await fetch('https://api.zyhap.com/api/v1/public/marketing/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': process.env.ZYHAP_API_KEY,
        'X-Workspace-ID': process.env.ZYHAP_WORKSPACE_ID
      },
      body: JSON.stringify(postData)
    });

    const result = await response.json();

    if (!response.ok) {
      const error = result.error;
      
      // Handle specific error codes
      switch (error.code) {
        case 'INVALID_API_KEY':
          throw new Error('API key is invalid. Please check your credentials.');
        
        case 'VALIDATION_ERROR':
          const validationErrors = error.details.map(d => d.message).join(', ');
          throw new Error(`Validation failed: ${validationErrors}`);
        
        case 'RATE_LIMIT_EXCEEDED':
          const retryAfter = response.headers.get('Retry-After') || 60;
          throw new Error(`Rate limit exceeded. Retry after ${retryAfter} seconds.`);
        
        case 'ACCOUNT_NOT_CONNECTED':
          throw new Error('Social account not connected. Please connect your account first.');
        
        default:
          throw new Error(`API Error: ${error.message} (Request ID: ${error.requestId})`);
      }
    }

    return result.data;
    
  } catch (error) {
    console.error('Post creation failed:', error.message);
    
    // Log for debugging
    if (error.requestId) {
      console.error('Request ID for support:', error.requestId);
    }
    
    throw error;
  }
}

Python

import requests
import time
from typing import Dict, Any

class ZyhapAPIError(Exception):
    def __init__(self, message: str, code: str = None, request_id: str = None):
        super().__init__(message)
        self.code = code
        self.request_id = request_id

class ZyhapAPI:
    def __init__(self, api_key: str, workspace_id: str):
        self.api_key = api_key
        self.workspace_id = workspace_id
        self.base_url = 'https://api.zyhap.com/api/v1/public/marketing'
    
    def create_post(self, post_data: Dict[str, Any], max_retries: int = 3) -> Dict[str, Any]:
        headers = {
            'Content-Type': 'application/json',
            'X-API-Key': self.api_key,
            'X-Workspace-ID': self.workspace_id
        }
        
        for attempt in range(max_retries + 1):
            try:
                response = requests.post(
                    f"{self.base_url}/posts",
                    json=post_data,
                    headers=headers,
                    timeout=30
                )
                
                result = response.json()
                
                if not response.ok:
                    error = result.get('error', {})
                    error_code = error.get('code')
                    error_message = error.get('message', 'Unknown error')
                    request_id = error.get('requestId')
                    
                    # Handle rate limiting with exponential backoff
                    if error_code == 'RATE_LIMIT_EXCEEDED' and attempt < max_retries:
                        retry_after = int(response.headers.get('Retry-After', 60))
                        print(f"Rate limited. Retrying after {retry_after} seconds...")
                        time.sleep(retry_after)
                        continue
                    
                    # Handle validation errors
                    if error_code == 'VALIDATION_ERROR':
                        details = error.get('details', [])
                        validation_errors = [d.get('message', '') for d in details]
                        error_message = f"Validation failed: {', '.join(validation_errors)}"
                    
                    raise ZyhapAPIError(error_message, error_code, request_id)
                
                return result['data']
                
            except requests.exceptions.RequestException as e:
                if attempt == max_retries:
                    raise ZyhapAPIError(f"Network error: {str(e)}")
                time.sleep(2 ** attempt)  # Exponential backoff
        
        raise ZyhapAPIError("Max retries exceeded")

# Usage example
try:
    api = ZyhapAPI(api_key, workspace_id)
    post = api.create_post({
        'content': {'text': 'Hello World!'},
        'platforms': [{'platformId': 'facebook', 'pageId': 'page_123'}],
        'publishDate': '2024-01-15T10:00:00Z'
    })
    print(f"Post created successfully: {post['id']}")
    
except ZyhapAPIError as e:
    print(f"API Error: {e}")
    if e.request_id:
        print(f"Request ID for support: {e.request_id}")
        
except Exception as e:
    print(f"Unexpected error: {e}")

Error Handling Best Practices

✅ Do

  • • Always check the response status before processing data
  • • Implement exponential backoff for rate-limited requests
  • • Log error details including request IDs for debugging
  • • Handle specific error codes with appropriate user messages
  • • Validate data client-side before sending requests
  • • Use timeouts to prevent hanging requests
  • • Implement retry logic for transient errors

❌ Don't

  • • Ignore error responses or status codes
  • • Show raw API error messages to end users
  • • Retry immediately without backoff on rate limits
  • • Log sensitive information like API keys in error messages
  • • Assume all errors are temporary and retry indefinitely
  • • Handle all errors the same way
  • • Forget to handle network timeouts and connection errors

💡 Pro Tip

Keep track of request IDs from error responses. When contacting support, provide the request ID along with the timestamp for faster troubleshooting.