Error Handling
Comprehensive guide to handling errors and troubleshooting issues with the Magnetite API.
Error Response Format
All error responses follow this consistent structure:
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error description",
"details": {
// Additional context when available
}
}
}
success
Always false
for error responses
error.code
Machine-readable error identifier for programmatic handling
error.message
Human-readable description suitable for display
HTTP Status Codes
Common Error Codes
Possible Causes
- API key is incorrect or malformed
- API key has been revoked or expired
- API key is not properly formatted in the Authorization header
Resolution
Verify your API key in the dashboard and ensure it's properly formatted in the Authorization header as 'Bearer sk_...'
Example Response
{
"success": false,
"error": {
"code": "INVALID_API_KEY",
"message": "Invalid API key provided"
}
}
Possible Causes
- Authorization header is missing from the request
- Header name is misspelled
- API key is missing from the header value
Resolution
Include the Authorization header with your API key: 'Authorization: Bearer sk_your_api_key'
Example Response
{
"success": false,
"error": {
"code": "MISSING_AUTHORIZATION",
"message": "Authorization header is required"
}
}
Possible Causes
- Account credit balance is too low
- Monthly credit limit has been exceeded
- Billing issue preventing credit usage
Resolution
Check your account balance in the dashboard and add more credits or upgrade your plan
Example Response
{
"success": false,
"error": {
"code": "INSUFFICIENT_CREDITS",
"message": "Insufficient credits. Required: 1, Available: 0"
}
}
Possible Causes
- Required fields are missing from the request
- Field values are in the wrong format
- JSON structure is malformed
Resolution
Check the API documentation for required fields and ensure all data is properly formatted
Example Response
{
"success": false,
"error": {
"code": "INVALID_REQUEST",
"message": "Missing required field: email",
"details": {
"field": "email",
"expected": "string",
"received": "undefined"
}
}
}
Possible Causes
- Sending requests too frequently
- Multiple API clients using the same key
- Bulk operations exceeding rate limits
Resolution
Implement exponential backoff and respect the rate limit headers. Consider batching requests with appropriate delays.
Example Response
{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Rate limit exceeded. Maximum 10 requests per 60 seconds allowed.",
"retryAfter": 45
}
}
Possible Causes
- Project ID is incorrect or malformed
- Project has been deleted
- API key doesn't have access to the project
Resolution
Verify the project ID in your dashboard and ensure your API key has the correct permissions
Example Response
{
"success": false,
"error": {
"code": "PROJECT_NOT_FOUND",
"message": "Project not found: abc123def456ghi789jkl012mno345pq"
}
}
Possible Causes
- Lead ID is incorrect or malformed
- Lead was not created successfully
- API key doesn't have access to the lead
Resolution
Verify the lead ID from the generation response and ensure it was created successfully
Example Response
{
"success": false,
"error": {
"code": "LEAD_NOT_FOUND",
"message": "Lead not found: lead_xyz789"
}
}
Possible Causes
- Insufficient data to generate personalized content
- External service temporarily unavailable
- Content generation constraints not met
Resolution
Try again with more detailed prospect information. If the issue persists, contact support.
Example Response
{
"success": false,
"error": {
"code": "GENERATION_FAILED",
"message": "Unable to generate lead magnet: insufficient company data",
"details": {
"reason": "Company website could not be analyzed",
"suggestion": "Provide more detailed company information"
}
}
}
Possible Causes
- Temporary server issue
- Database connectivity problem
- Unexpected system error
Resolution
This is usually temporary. Wait a moment and try again. If the issue persists, contact support.
Example Response
{
"success": false,
"error": {
"code": "INTERNAL_SERVER_ERROR",
"message": "An unexpected error occurred. Please try again later."
}
}
Error Handling Best Practices
Don't rely solely on the response body. HTTP status codes provide important context:
async function handleApiResponse(response) {
if (!response.ok) {
const errorData = await response.json();
switch (response.status) {
case 401:
throw new AuthenticationError(errorData.error.message);
case 402:
throw new InsufficientCreditsError(errorData.error.message);
case 429:
throw new RateLimitError(errorData.error.message, errorData.error.retryAfter);
case 500:
throw new ServerError(errorData.error.message);
default:
throw new ApiError(errorData.error.message, response.status);
}
}
return response.json();
}
Some errors are transient and should be retried with exponential backoff:
async function makeRequestWithRetry(url, options, maxRetries = 3) {
const retryableStatuses = [429, 500, 502, 503, 504];
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (response.ok) {
return await response.json();
}
if (!retryableStatuses.includes(response.status)) {
throw new Error('Non-retryable error: ' + response.status);
}
if (attempt === maxRetries - 1) {
throw new Error('Max retries exceeded');
}
const delay = Math.min(1000 * Math.pow(2, attempt), 10000);
console.log(`Retrying in ${delay}ms (attempt ${attempt + 1})`);
await new Promise(resolve => setTimeout(resolve, delay));
} catch (error) {
if (attempt === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, attempt)));
}
}
}
Different error types require different logging levels:
function logApiError(error, context) {
const logData = {
timestamp: new Date().toISOString(),
context,
error: {
code: error.code,
message: error.message,
status: error.status
}
};
switch (error.status) {
case 401:
case 402:
// Authentication/billing issues - warn level
console.warn('API authentication/billing error:', logData);
break;
case 429:
// Rate limiting - info level (expected during high usage)
console.info('API rate limit hit:', logData);
break;
case 500:
case 502:
case 503:
case 504:
// Server errors - error level
console.error('API server error:', logData);
break;
default:
// Client errors - debug level
console.debug('API client error:', logData);
}
}
Convert technical error messages into user-friendly ones:
function getUserFriendlyMessage(error) {
const friendlyMessages = {
INVALID_API_KEY: 'There was an authentication issue. Please check your API configuration.',
INSUFFICIENT_CREDITS: 'You don\'t have enough credits to complete this request. Please add more credits to your account.',
RATE_LIMIT_EXCEEDED: 'You\'re sending requests too quickly. Please wait a moment before trying again.',
GENERATION_FAILED: 'We couldn\'t generate a lead magnet with the provided information. Please try with more detailed data.',
INTERNAL_SERVER_ERROR: 'Something went wrong on our end. Please try again in a few moments.'
};
return friendlyMessages[error.code] || 'An unexpected error occurred. Please try again or contact support if the issue persists.';
}
Need More Help?
If you're experiencing errors not covered here or need additional assistance: