Error Handling
Understanding and handling API errors effectively.
Overview
The Heydeo API uses conventional HTTP response codes to indicate the success or failure of requests. Errors include detailed information to help you debug and resolve issues quickly.
💡 Tip: All error responses include a code field for programmatic handling and a message field with human-readable details.
HTTP Status Codes
| Code | Status | Description |
|---|---|---|
200 | OK | Request succeeded |
201 | Created | Resource created successfully |
204 | No Content | Request succeeded, no content to return |
400 | Bad Request | Invalid request parameters |
401 | Unauthorized | Invalid or missing API key |
403 | Forbidden | API key lacks required permissions |
404 | Not Found | Resource doesn't exist |
409 | Conflict | Request conflicts with existing resource |
422 | Unprocessable Entity | Request syntax valid but semantically incorrect |
429 | Too Many Requests | Rate limit exceeded |
500 | Internal Server Error | Server error occurred |
503 | Service Unavailable | Temporary server overload or maintenance |
Error Response Format
All errors follow this consistent structure:
{
"error": {
"code": "validation_error",
"message": "Invalid request parameters",
"details": [
{
"field": "origin_country",
"message": "Must be a valid ISO 3166-1 alpha-2 country code",
"value": "USA"
}
],
"request_id": "req_abc123xyz",
"documentation_url": "https://docs.heydeo.ai/errors#validation_error"
}
}Error Codes
Authentication Errors
| Code | Description |
|---|---|
invalid_api_key | API key is invalid or revoked |
missing_api_key | No API key provided in request |
insufficient_permissions | API key lacks required permissions |
Validation Errors
| Code | Description |
|---|---|
validation_error | Request parameters failed validation |
invalid_country_code | Invalid ISO country code provided |
invalid_hs_code | HS code format is invalid |
missing_required_field | Required field is missing |
Resource Errors
| Code | Description |
|---|---|
resource_not_found | Requested resource doesn't exist |
resource_already_exists | Resource with identifier already exists |
resource_locked | Resource is locked for editing |
Rate Limit Errors
| Code | Description |
|---|---|
rate_limit_exceeded | Too many requests in time window |
daily_limit_exceeded | Daily request quota exceeded |
Server Errors
| Code | Description |
|---|---|
internal_server_error | Unexpected server error occurred |
service_unavailable | Service temporarily unavailable |
gateway_timeout | Request timeout exceeded |
Handling Errors in Code
JavaScript/TypeScript
import { HeydeoClient, HeydeoError } from '@heydeo/sdk';
const client = new HeydeoClient({ apiKey: 'your-api-key' });
try {
const shipments = await client.shipments.search({
origin: 'US',
destination: 'CN'
});
} catch (error) {
if (error instanceof HeydeoError) {
console.error('API Error:', {
code: error.code,
message: error.message,
status: error.status,
requestId: error.requestId,
details: error.details
});
// Handle specific errors
switch (error.code) {
case 'invalid_api_key':
// Refresh or update API key
break;
case 'rate_limit_exceeded':
// Implement backoff and retry
const retryAfter = error.retryAfter || 60;
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
// Retry request...
break;
case 'validation_error':
// Fix validation issues
console.error('Validation errors:', error.details);
break;
default:
// Handle other errors
console.error('Unexpected error:', error);
}
} else {
// Handle non-API errors
console.error('Network or unexpected error:', error);
}
}Python
from heydeo import HeydeoClient
from heydeo.exceptions import (
HeydeoError,
AuthenticationError,
ValidationError,
RateLimitError,
ResourceNotFoundError
)
import time
client = HeydeoClient(api_key="your-api-key")
try:
shipments = client.shipments.search(
origin="US",
destination="CN"
)
except AuthenticationError as e:
print(f"Authentication failed: {e.message}")
print(f"Error code: {e.code}")
# Update or refresh API key
except ValidationError as e:
print(f"Validation error: {e.message}")
print(f"Field errors: {e.details}")
# Fix validation issues
except RateLimitError as e:
print(f"Rate limit exceeded: {e.message}")
retry_after = e.retry_after or 60
print(f"Retrying after {retry_after} seconds...")
time.sleep(retry_after)
# Retry request
except ResourceNotFoundError as e:
print(f"Resource not found: {e.message}")
# Handle missing resource
except HeydeoError as e:
print(f"API error: {e.message}")
print(f"Status: {e.status}")
print(f"Request ID: {e.request_id}")
# Handle other API errors
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Handle non-API errorsRetry Strategies
Implement intelligent retry logic for transient errors:
async function retryWithBackoff(fn, maxRetries = 3, baseDelay = 1000) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
// Don't retry on client errors (4xx except 429)
if (error.status >= 400 && error.status < 500 && error.status !== 429) {
throw error;
}
// Last attempt, throw error
if (attempt === maxRetries - 1) {
throw error;
}
// Calculate delay with exponential backoff
const delay = error.retryAfter
? error.retryAfter * 1000
: baseDelay * Math.pow(2, attempt);
console.log(`Retry attempt ${attempt + 1} after ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// Usage
const shipments = await retryWithBackoff(() =>
client.shipments.search({ origin: 'US' })
);Best Practices
- 🔍 Check error codes - Use the
codefield for programmatic handling - 📝 Log request IDs - Include
request_idwhen contacting support - 🔄 Implement retry logic - Retry transient errors (5xx, 429) with backoff
- ❌ Don't retry 4xx errors - Client errors won't succeed without changes
- ⚠️ Validate before sending - Reduce errors by validating inputs client-side
- 📊 Monitor error rates - Track errors to identify integration issues
- 🛡️ Handle gracefully - Provide user-friendly error messages
Debugging Errors
When troubleshooting errors, collect this information:
- Request ID from the error response
- Full error response body
- HTTP status code
- Request parameters and headers (remove sensitive data)
- Timestamp of the request
- SDK version (if applicable)
Contact support with this information for faster resolution:
support@heydeo.aiError Response Examples
Validation Error
{
"error": {
"code": "validation_error",
"message": "Invalid request parameters",
"details": [
{
"field": "origin_country",
"message": "Must be a valid ISO 3166-1 alpha-2 country code",
"value": "USA"
},
{
"field": "hs_code",
"message": "HS code must be 6-10 digits",
"value": "12345"
}
],
"request_id": "req_abc123",
"documentation_url": "https://docs.heydeo.ai/errors#validation_error"
}
}Authentication Error
{
"error": {
"code": "invalid_api_key",
"message": "The API key provided is invalid or has been revoked",
"request_id": "req_xyz789",
"documentation_url": "https://docs.heydeo.ai/errors#invalid_api_key"
}
}Rate Limit Error
{
"error": {
"code": "rate_limit_exceeded",
"message": "Rate limit of 60 requests per minute exceeded",
"retry_after": 45,
"request_id": "req_def456",
"documentation_url": "https://docs.heydeo.ai/errors#rate_limit_exceeded"
}
}