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

4xx
Client Errors
Errors caused by the client request
400 Bad RequestInvalid request format
401 UnauthorizedAuthentication failed
402 Payment RequiredInsufficient credits
404 Not FoundResource not found
422 UnprocessableGeneration failed
429 Too Many RequestsRate limit exceeded
5xx
Server Errors
Errors on Magnetite's side
500 Internal Server ErrorUnexpected server error
502 Bad GatewayUpstream service error
503 Service UnavailableTemporary unavailability
504 Gateway TimeoutRequest timeout

Common Error Codes

INVALID_API_KEY
401
The provided API key is invalid or has been revoked.

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"
  }
}
MISSING_AUTHORIZATION
401
No Authorization header was provided with the request.

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"
  }
}
INSUFFICIENT_CREDITS
402
Your account does not have enough credits to complete this request.

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"
  }
}
INVALID_REQUEST
400
The request body contains invalid or missing required fields.

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"
    }
  }
}
RATE_LIMIT_EXCEEDED
429
Too many requests have been made in the current time window.

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
  }
}
PROJECT_NOT_FOUND
404
The specified project ID does not exist or is not accessible.

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"
  }
}
LEAD_NOT_FOUND
404
The specified lead ID does not exist or is not accessible.

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"
  }
}
GENERATION_FAILED
422
The lead magnet generation process failed due to an internal error.

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"
    }
  }
}
INTERNAL_SERVER_ERROR
500
An unexpected error occurred on our servers.

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

1. Always Check HTTP Status Codes

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();
}
2. Implement Retry Logic

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)));
    }
  }
}
3. Log Errors Appropriately

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);
  }
}
4. Provide User-Friendly Messages

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: