Skip to main content

API Error Handling

Complete guide to handling API errors in Netasampark.

Error Response Format

All API errors follow a consistent format:

{
"success": false,
"error_code": "error_code",
"message": "Human-readable error message",
"details": {
// Additional error details (optional)
}
}

HTTP Status Codes

Status CodeDescriptionError Code
400Bad Requestvalidation_error, bad_request
401Unauthorizedunauthorized
403Forbiddenforbidden
404Not Foundnot_found
422Unprocessable Entityvalidation_error
429Too Many Requestsrate_limit_exceeded
500Internal Server Errorserver_error
503Service Unavailableservice_unavailable

Common Error Codes

Validation Errors (422)

{
"success": false,
"error_code": "validation_error",
"message": "The given data was invalid.",
"details": {
"email": ["The email field is required."],
"password": ["The password must be at least 8 characters."]
}
}

Unauthorized (401)

{
"success": false,
"error_code": "unauthorized",
"message": "Authentication required to access this resource."
}

Forbidden (403)

{
"success": false,
"error_code": "forbidden",
"message": "You do not have permission to perform this action."
}

Not Found (404)

{
"success": false,
"error_code": "not_found",
"message": "The requested resource was not found."
}

Rate Limit Exceeded (429)

{
"success": false,
"error_code": "rate_limit_exceeded",
"message": "Too many requests. Please try again later.",
"retry_after": 60
}

Server Error (500)

{
"success": false,
"error_code": "server_error",
"message": "An unexpected error occurred.",
"details": "Error details (only in development)"
}

Error Handling Examples

JavaScript/TypeScript

async function handleApiRequest(url, options) {
try {
const response = await fetch(url, options);
const data = await response.json();

if (!data.success) {
switch (data.error_code) {
case 'validation_error':
// Handle validation errors
console.error('Validation errors:', data.details);
break;
case 'unauthorized':
// Redirect to login
window.location.href = '/login';
break;
case 'rate_limit_exceeded':
// Retry after delay
await new Promise(resolve =>
setTimeout(resolve, data.retry_after * 1000)
);
return handleApiRequest(url, options);
default:
console.error('API Error:', data.message);
}
throw new Error(data.message);
}

return data.data;
} catch (error) {
if (error instanceof TypeError) {
// Network error
console.error('Network error:', error.message);
} else {
// API error
console.error('API error:', error.message);
}
throw error;
}
}

PHP

try {
$response = $client->request('GET', '/api/endpoint');
$data = json_decode($response->getBody(), true);

if (!$data['success']) {
switch ($data['error_code']) {
case 'validation_error':
// Handle validation errors
foreach ($data['details'] as $field => $errors) {
echo "{$field}: " . implode(', ', $errors) . "\n";
}
break;
case 'unauthorized':
// Redirect to login
header('Location: /login');
exit;
case 'rate_limit_exceeded':
// Wait and retry
sleep($data['retry_after']);
// Retry request
break;
default:
throw new Exception($data['message']);
}
}

return $data['data'];
} catch (Exception $e) {
error_log('API Error: ' . $e->getMessage());
throw $e;
}

Python

import requests
import time

def handle_api_request(url, headers, data=None):
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()

result = response.json()

if not result.get('success'):
error_code = result.get('error_code')

if error_code == 'validation_error':
# Handle validation errors
for field, errors in result.get('details', {}).items():
print(f"{field}: {', '.join(errors)}")
elif error_code == 'unauthorized':
# Redirect to login
return redirect('/login')
elif error_code == 'rate_limit_exceeded':
# Wait and retry
time.sleep(result.get('retry_after', 60))
return handle_api_request(url, headers, data)
else:
raise Exception(result.get('message'))

return result.get('data')
except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
raise

Best Practices

  1. Always Check Success Field: Don't assume success based on HTTP status
  2. Handle All Error Codes: Implement handling for all error types
  3. User-Friendly Messages: Display user-friendly error messages
  4. Log Errors: Log errors for debugging
  5. Retry Logic: Implement retry logic for transient errors
  6. Graceful Degradation: Handle errors gracefully without breaking UX

Error Recovery

Automatic Retry

For transient errors (500, 503, 429):

  • Implement exponential backoff
  • Limit retry attempts
  • Log retry attempts

User Notification

For user-facing errors:

  • Display clear error messages
  • Provide actionable guidance
  • Offer alternative actions

Next Steps


Need help? Contact Support