Error Handling
The Connix API uses conventional HTTP response codes to indicate the success or failure of requests. Error responses include detailed information to help you identify and resolve issues quickly.
Error Response Format
Section titled “Error Response Format”All error responses follow a consistent JSON structure:
{ "error": { "code": "error_code", "message": "Human-readable error description", "details": "Additional context or debugging information", "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Error Object Properties
Section titled “Error Object Properties”Property | Type | Description |
---|---|---|
code | string | Machine-readable error identifier |
message | string | Human-readable error description |
details | string/object | Additional context or validation errors |
request_id | string | Unique identifier for the request |
timestamp | string | ISO 8601 timestamp when error occurred |
HTTP Status Codes
Section titled “HTTP Status Codes”2xx Success Codes
Section titled “2xx Success Codes”Code | Status | Description |
---|---|---|
200 | OK | Request succeeded |
201 | Created | Resource created successfully |
202 | Accepted | Request accepted for processing |
204 | No Content | Request succeeded with no response body |
4xx Client Error Codes
Section titled “4xx Client Error Codes”Code | Status | Description |
---|---|---|
400 | Bad Request | Invalid request syntax or parameters |
401 | Unauthorized | Authentication required or invalid |
403 | Forbidden | Insufficient permissions for request |
404 | Not Found | Requested resource does not exist |
405 | Method Not Allowed | HTTP method not supported for endpoint |
409 | Conflict | Request conflicts with current resource state |
422 | Unprocessable Entity | Request syntax valid but semantically incorrect |
429 | Too Many Requests | Rate limit exceeded |
5xx Server Error Codes
Section titled “5xx Server Error Codes”Code | Status | Description |
---|---|---|
500 | Internal Server Error | Unexpected server error |
502 | Bad Gateway | Invalid response from upstream server |
503 | Service Unavailable | Server temporarily unavailable |
504 | Gateway Timeout | Timeout waiting for upstream server |
Common Error Codes
Section titled “Common Error Codes”Authentication Errors
Section titled “Authentication Errors”invalid_api_key
Section titled “invalid_api_key”HTTP Status: 401 Unauthorized
{ "error": { "code": "invalid_api_key", "message": "The provided API key is invalid or has been revoked", "details": "API key format should be: cx_[32 hexadecimal characters]", "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Causes:
- API key is malformed
- API key has been revoked
- API key has expired
- Wrong authentication method used
Solutions:
- Verify API key format and validity
- Check if key has been revoked in console
- Generate a new API key if needed
- Ensure proper authentication header format
expired_token
Section titled “expired_token”HTTP Status: 401 Unauthorized
{ "error": { "code": "expired_token", "message": "The access token has expired", "details": "Token expired at 2024-01-15T15:00:00Z", "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Solutions:
- Use refresh token to obtain new access token
- Re-authenticate with OAuth2 flow
- Check token expiration time before making requests
insufficient_scope
Section titled “insufficient_scope”HTTP Status: 403 Forbidden
{ "error": { "code": "insufficient_scope", "message": "The request requires higher privileges than provided by the access token", "details": { "required_scopes": ["projects:write"], "provided_scopes": ["projects:read"] }, "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Solutions:
- Request new token with required scopes
- Update API key permissions
- Contact administrator for permission changes
Validation Errors
Section titled “Validation Errors”validation_error
Section titled “validation_error”HTTP Status: 400 Bad Request
{ "error": { "code": "validation_error", "message": "One or more request parameters are invalid", "details": [ { "field": "name", "message": "Name is required and cannot be empty", "code": "required" }, { "field": "config.temperature", "message": "Temperature must be between 0 and 2", "code": "out_of_range", "min": 0, "max": 2, "provided": 3.5 } ], "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Common Field Validation Errors:
Field Type | Error Code | Description |
---|---|---|
Required fields | required | Field is missing or empty |
String length | too_short / too_long | String length outside limits |
Numeric range | out_of_range | Number outside valid range |
Format | invalid_format | Invalid format (email, URL, etc.) |
Enum | invalid_choice | Value not in allowed options |
invalid_json
Section titled “invalid_json”HTTP Status: 400 Bad Request
{ "error": { "code": "invalid_json", "message": "Request body contains invalid JSON", "details": "Unexpected token '}' at position 45", "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Solutions:
- Validate JSON syntax
- Ensure proper content-type header
- Check for trailing commas or syntax errors
Resource Errors
Section titled “Resource Errors”resource_not_found
Section titled “resource_not_found”HTTP Status: 404 Not Found
{ "error": { "code": "resource_not_found", "message": "The requested resource was not found", "details": { "resource_type": "project", "resource_id": "proj_1234567890abcdef" }, "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Common Resource Types:
project
- Project not foundagent
- Agent not foundapi_key
- API key not foundorganization
- Organization not found
resource_conflict
Section titled “resource_conflict”HTTP Status: 409 Conflict
{ "error": { "code": "resource_conflict", "message": "A resource with the same identifier already exists", "details": { "resource_type": "project", "conflicting_field": "name", "conflicting_value": "My Project" }, "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Solutions:
- Use different name or identifier
- Check if resource already exists
- Update existing resource instead of creating new one
Rate Limiting Errors
Section titled “Rate Limiting Errors”rate_limit_exceeded
Section titled “rate_limit_exceeded”HTTP Status: 429 Too Many Requests
{ "error": { "code": "rate_limit_exceeded", "message": "Rate limit exceeded for this endpoint", "details": { "limit": 100, "window": "1 minute", "retry_after": 45 }, "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Response Headers:
X-RateLimit-Limit: 100X-RateLimit-Remaining: 0X-RateLimit-Reset: 1705334445Retry-After: 45
Solutions:
- Wait for rate limit window to reset
- Implement exponential backoff
- Reduce request frequency
- Consider upgrading to higher tier
Server Errors
Section titled “Server Errors”internal_error
Section titled “internal_error”HTTP Status: 500 Internal Server Error
{ "error": { "code": "internal_error", "message": "An unexpected error occurred while processing your request", "details": "Please try again later or contact support if the issue persists", "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Solutions:
- Retry request after a delay
- Check API status page
- Contact support with request ID
service_unavailable
Section titled “service_unavailable”HTTP Status: 503 Service Unavailable
{ "error": { "code": "service_unavailable", "message": "The service is temporarily unavailable", "details": "Scheduled maintenance in progress. Service will resume at 17:00 UTC", "request_id": "req_1234567890abcdef", "timestamp": "2024-01-15T16:20:00Z" }}
Solutions:
- Wait and retry after maintenance window
- Check status page for updates
- Implement retry logic with exponential backoff
Error Handling Best Practices
Section titled “Error Handling Best Practices”1. Implement Proper Error Handling
Section titled “1. Implement Proper Error Handling”// JavaScript exampletry { const response = await fetch('https://api.connix.io/api/v1/projects', { headers: { 'X-API-Key': apiKey, 'Content-Type': 'application/json' } });
if (!response.ok) { const errorData = await response.json(); throw new ConnixAPIError(errorData.error, response.status); }
const data = await response.json(); return data;} catch (error) { if (error instanceof ConnixAPIError) { // Handle specific API errors switch (error.code) { case 'invalid_api_key': // Redirect to authentication break; case 'rate_limit_exceeded': // Implement retry with backoff break; default: // Log error and show user-friendly message console.error('API Error:', error); } } else { // Handle network or other errors console.error('Network Error:', error); }}
2. Implement Exponential Backoff
Section titled “2. Implement Exponential Backoff”# Python exampleimport timeimport requestsfrom requests.adapters import HTTPAdapterfrom requests.packages.urllib3.util.retry import Retry
def create_session_with_retries(): session = requests.Session()
retry_strategy = Retry( total=3, status_forcelist=[429, 500, 502, 503, 504], backoff_factor=1, allowed_methods=["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"] )
adapter = HTTPAdapter(max_retries=retry_strategy) session.mount("http://", adapter) session.mount("https://", adapter)
return session
def make_api_request(url, headers, data=None): session = create_session_with_retries()
try: if data: response = session.post(url, headers=headers, json=data) else: response = session.get(url, headers=headers)
response.raise_for_status() return response.json()
except requests.exceptions.HTTPError as e: if e.response.status_code == 429: # Handle rate limiting retry_after = int(e.response.headers.get('Retry-After', 60)) time.sleep(retry_after) return make_api_request(url, headers, data) else: # Handle other HTTP errors error_data = e.response.json() raise ConnixAPIException(error_data['error'])
except requests.exceptions.RequestException as e: # Handle network errors raise NetworkException(str(e))
3. Log and Monitor Errors
Section titled “3. Log and Monitor Errors”// Go examplepackage main
import ( "encoding/json" "fmt" "log" "net/http" "time")
type ConnixError struct { Code string `json:"code"` Message string `json:"message"` Details interface{} `json:"details"` RequestID string `json:"request_id"` Timestamp time.Time `json:"timestamp"`}
func (e *ConnixError) Error() string { return fmt.Sprintf("Connix API Error [%s]: %s", e.Code, e.Message)}
func handleAPIError(resp *http.Response) error { var errorResp struct { Error ConnixError `json:"error"` }
if err := json.NewDecoder(resp.Body).Decode(&errorResp); err != nil { return fmt.Errorf("failed to decode error response: %w", err) }
// Log error with context log.Printf("API Error: %s (Request ID: %s, Status: %d)", errorResp.Error.Code, errorResp.Error.RequestID, resp.StatusCode)
// Handle specific error types switch errorResp.Error.Code { case "rate_limit_exceeded": return &RateLimitError{ConnixError: errorResp.Error} case "invalid_api_key", "expired_token": return &AuthenticationError{ConnixError: errorResp.Error} case "insufficient_scope": return &AuthorizationError{ConnixError: errorResp.Error} default: return &errorResp.Error }}
4. User-Friendly Error Messages
Section titled “4. User-Friendly Error Messages”Map API error codes to user-friendly messages:
const ERROR_MESSAGES = { 'invalid_api_key': 'Please check your API key and try again.', 'expired_token': 'Your session has expired. Please sign in again.', 'insufficient_scope': 'You don\'t have permission to perform this action.', 'rate_limit_exceeded': 'Too many requests. Please wait a moment and try again.', 'validation_error': 'Please check your input and try again.', 'resource_not_found': 'The requested resource could not be found.', 'resource_conflict': 'A resource with this name already exists.', 'internal_error': 'Something went wrong on our end. Please try again later.', 'service_unavailable': 'The service is temporarily unavailable. Please try again later.'};
function getErrorMessage(errorCode) { return ERROR_MESSAGES[errorCode] || 'An unexpected error occurred. Please try again.';}
Debugging Tips
Section titled “Debugging Tips”1. Use Request IDs
Section titled “1. Use Request IDs”Every error response includes a unique request_id
. Include this when contacting support:
curl -X GET "https://api.connix.io/api/v1/projects" \ -H "X-API-Key: invalid_key" \ -v
Response headers will include:
X-Request-ID: req_1234567890abcdef
2. Check API Status
Section titled “2. Check API Status”Before debugging, check the API status page:
- Status Page: https://status.connix.io
- Service Health: https://api.connix.io/health
3. Validate API Keys
Section titled “3. Validate API Keys”Test your API key with a simple request:
curl -X GET "https://api.connix.io/api/v1/hello?name=Test" \ -H "X-API-Key: your_api_key_here"
Expected response:
{ "message": "Hello Test! Welcome to Connix API v1"}
4. Monitor Rate Limits
Section titled “4. Monitor Rate Limits”Check rate limit headers in responses:
curl -X GET "https://api.connix.io/api/v1/projects" \ -H "X-API-Key: your_api_key_here" \ -I
Response headers:
X-RateLimit-Limit: 100X-RateLimit-Remaining: 87X-RateLimit-Reset: 1705334400
Error Webhooks
Section titled “Error Webhooks”Configure webhooks to receive notifications about critical errors:
Webhook Payload
Section titled “Webhook Payload”{ "event": "error.occurred", "timestamp": "2024-01-15T16:20:00Z", "data": { "error": { "code": "internal_error", "message": "Database connection failed", "severity": "high", "affected_resources": ["proj_1234567890abcdef"] }, "user_id": "user_1234567890abcdef", "request_id": "req_1234567890abcdef" }}
Webhook Configuration
Section titled “Webhook Configuration”curl -X POST "https://api.connix.io/api/v1/webhooks" \ -H "X-API-Key: your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "url": "https://yourapp.com/webhooks/connix", "events": ["error.occurred"], "filters": { "severity": ["high", "critical"] } }'
Getting Help
Section titled “Getting Help”Support Channels
Section titled “Support Channels”- Documentation: https://docs.connix.io
- Community Forum: https://community.connix.io
- Support Email: engineering@connix.io
- Status Page: https://status.connix.io
When Contacting Support
Section titled “When Contacting Support”Include the following information:
- Request ID from error response
- Complete error message and code
- Steps to reproduce the issue
- API endpoint and HTTP method used
- Timestamp when error occurred
- Expected vs. actual behavior
Emergency Support
Section titled “Emergency Support”For critical production issues:
- Priority Support: Available for Pro and Enterprise plans
- Emergency Hotline: Contact through console.connix.io
- Escalation: Include severity level and business impact
Next Steps
Section titled “Next Steps”- API Overview - General API information and getting started
- Authentication - Authentication methods and security
- Projects API - Project management endpoints
- Agents API - Agent creation and management