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
Request successful, data returned
Resource created successfully
Request successful, no data returned
❌ Error Codes
Invalid request data or parameters
Invalid or missing API key
Insufficient permissions, or the module is not available in the country of the branch the key acts in (code ##MODULE_NOT_IN_COUNTRY).
Resource not found
Rate limit exceeded
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
| Field | Type | Description |
|---|---|---|
| success | boolean | Always false for error responses |
| error.code | string | Machine-readable error code |
| error.message | string | Human-readable error description |
| error.details | array | Detailed validation errors (when applicable) |
| error.requestId | string | Unique identifier for debugging |
Common Error Codes
Understanding these error codes will help you handle specific scenarios in your application.
Authentication Errors
The provided API key is invalid or expired
X-Workspace-ID header is required
API key lacks required permissions
Validation Errors
Request data validation failed
Date must be in ISO 8601 format
Content exceeds platform limits
Platform Errors
Social account not linked to workspace
Access to platform has been revoked
Media format not supported by platform
Rate Limiting
Too many requests, retry after specified time
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.