Error Handling
The error handling guide provides comprehensive solutions for common issues developers may encounter when using the Moitribe PHP SDK. This helps with debugging, troubleshooting and providing better user experiences.
Overview
This guide covers:
- Common error scenarios and their solutions
- Debugging techniques
- Best practices for error prevention
- Network and connectivity issues
- API response interpretation
- Recovery strategies
Common Error Categories
Authentication Errors
- Invalid credentials - Wrong game ID, channel ID, or player ID
- Player not found - Player doesn't exist in Moitribe system
- Session expired - Authentication token has expired
- Rate limiting - Too many authentication attempts
Tournament Errors
- Tournament not found - Invalid tournament ID
- Tournament not active - Tournament hasn't started or has ended
- Already joined - Player already registered
- Tournament full - Maximum participants reached
- Invalid score - Negative or unrealistic score values
Leaderboard Errors
- Leaderboard not found - Invalid leaderboard ID
- Invalid score - Negative or unrealistic score values
Profile Errors
- Invalid player ID - Player doesn't exist
- Permission denied - No access to profile data
Network & API Errors
- Connection timeout - Network connectivity issues
- API unavailable - Moitribe services temporarily down
- Rate limiting - Too many requests in short time
Error Code Reference
HTTP Status Codes
- 200 - Success
- 400 - Bad Request (invalid parameters)
- 401 - Unauthorized (authentication required)
- 403 - Forbidden (insufficient permissions)
- 404 - Not Found (resource doesn't exist)
- 500 - Server Error
SDK Error Codes
- InvalidArgumentException - Invalid input parameters
- Exception - General API errors
Debugging Techniques
1. Enable Error Reporting
// Enable comprehensive error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', '/path/to/error.log');
// Custom error handler
set_error_handler(function($severity, $errno, $errstr) {
// Log error with context
error_log("[$severity] [$errno] $errstr]");
// Send notifications for critical errors
if ($severity === 'critical') {
sendAdminAlert($errno, $errstr);
}
});
2. Use Structured Logging
function logApiCall($method, $url, $data = []) {
$context = [
'method' => $method,
'url' => $url,
'request_data' => $data,
'timestamp' => date('Y-m-d H:i:s'),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
];
$start = microtime(true);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'User-Agent: ' . $context['user_agent']
]);
$result = curl_exec($ch);
$end = microtime(true);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = curl_exec($ch);
curl_close($ch);
// Log the API call
logApiCall($method, $url, $data, [
'http_code' => $httpCode,
'response' => $response,
'duration' => ($end - $start),
'context' => $context
]);
return $result;
}
3. Network Diagnostics
function checkNetworkConnectivity() {
$testUrl = 'https://api.moitribe.com/health';
$ch = curl_init($testUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
return ['status' => 'healthy', 'message' => 'API is accessible'];
} else {
return ['status' => 'unhealthy', 'message' => 'API is not accessible', 'http_code' => $httpCode];
}
}
}
Recovery Strategies
1. Automatic Retry with Exponential Backoff
function apiCallWithRetry($method, $url, $data = [], $maxRetries = 3) {
$attempt = 0;
$baseDelay = 1; // Start with 1 second delay
while ($attempt < $maxRetries) {
try {
$result = $this->apiCall($method, $url, $data);
if ($result !== false) {
return $result;
}
$attempt++;
// Exponential backoff
$delay = $baseDelay * pow(2, $attempt);
sleep($delay * 1000000); // Convert to microseconds
} catch (Exception $e) {
if ($attempt >= $maxRetries) {
throw new Exception("Max retries exceeded");
}
return false;
}
}
return $result;
}
2. Circuit Breaker Pattern
function apiCallWithCircuitBreaker($method, $url, $data = [], $maxRetries = 3) {
$attempt = 0;
$baseDelay = 1;
while ($attempt < $maxRetries) {
try {
$result = $this->apiCall($method, $url, $data);
if ($result !== false) {
return $result;
}
$attempt++;
// Check for specific error types
if (strpos($e->getMessage(), 'timeout') !== false) {
// Network error - try different approach
$delay = min($baseDelay * 2, $attempt);
} elseif (strpos($e->getMessage(), 'rate_limit') !== false) {
// Rate limiting - wait longer
$delay = min($baseDelay * 5, $attempt);
} else {
// Other error - use standard delay
$delay = $baseDelay;
}
sleep($delay * 1000000);
}
} catch (Exception $e) {
$attempt++;
if ($attempt >= $maxRetries) {
throw new Exception("Circuit breaker triggered");
}
return false;
}
}
return $result;
}
Best Practices
1. Prevent Errors
- Validate all inputs before API calls
- Use type hints and strict validation
- Check resource availability before operations
- Implement proper authentication flows
- Handle Network Issues
- Use connection timeouts and retry mechanisms
- Implement fallback systems for critical operations
- Monitor API health and set up alerts
- Provide Clear Feedback
- Always return actionable error messages
- Include error codes for reference
- Suggest specific solutions when possible
- Document Everything
- Document error scenarios and resolutions
- Provide troubleshooting checklists
Support Information
For additional help with Moitribe PHP SDK:
- Documentation: See the other sections in this documentation for comprehensive API details
- Developer Portal: Moitribe Developer Portal
- Support Email: support@moitribe.com
- Community Forums: Moitribe Community Forums
Quick Reference
| Error | Solution | Quick Fix |
|---|---|---|
| Invalid Game ID | Check your game configuration | |
| Player not found | Use force login to create player | |
| Session expired | Refresh authentication token | |
| Network timeout | Check internet connection | |
| Rate limiting | Wait and retry | |
| API unavailable | Check service status |
This error handling guide will help developers quickly identify and resolve issues, reducing support tickets and improving user satisfaction.