Error Handling

Learn how to handle errors, implement retry logic, and debug issues effectively

Overview

Wazza Engine uses conventional HTTP status codes and structured error responses to indicate success or failure of API requests. This guide covers common error scenarios and how to handle them gracefully.

Error Response Format

All errors follow a consistent JSON structure:

{
  "error": {
    "code": "INVALID_PROMPT",
    "message": "The prompt violates content safety policies",
    "type": "validation_error",
    "details": {
      "field": "prompt",
      "reason": "contains_nsfw_content"
    },
    "requestId": "req_abc123",
    "timestamp": "2025-10-22T10:30:00Z"
  }
}

HTTP Status Codes

2xx Success

  • 200 OK: Request succeeded
  • 201 Created: Resource created successfully
  • 202 Accepted: Request accepted for async processing

4xx Client Errors

  • 400 Bad Request: Invalid request parameters
  • 401 Unauthorized: Missing or invalid API key
  • 402 Payment Required: Insufficient credits
  • 403 Forbidden: Access denied
  • 404 Not Found: Resource doesn't exist
  • 422 Unprocessable Entity: Validation error
  • 429 Too Many Requests: Rate limit exceeded

5xx Server Errors

  • 500 Internal Server Error: Unexpected server error
  • 502 Bad Gateway: Upstream provider error
  • 503 Service Unavailable: Temporary outage
  • 504 Gateway Timeout: Provider timeout

Common Error Codes

CodeDescriptionResolution
INVALID_API_KEYAPI key is missing or invalidCheck your API key
INSUFFICIENT_CREDITSNot enough credits for operationPurchase more credits
RATE_LIMIT_EXCEEDEDToo many requestsWait and retry with backoff
INVALID_PROMPTPrompt violates content policyModify prompt to be compliant
MODEL_NOT_AVAILABLEModel is temporarily unavailableTry alternative model or retry
PROVIDER_ERRORUpstream provider failedRetry or use fallback provider
JOB_TIMEOUTGeneration took too longReduce complexity or retry
INVALID_PARAMETERSInvalid request parametersCheck parameter documentation

Handling Errors in Code

Basic Error Handling

import WazzaEngine from '@wazza/engine';

const wazza = new WazzaEngine({
  apiKey: process.env.WAZZA_API_KEY
});

try {
  const response = await wazza.generate({
    provider: 'openai',
    model: 'sora-2-pro',
    prompt: 'A beautiful sunset'
  });

  console.log('Success:', response.jobId);
} catch (error) {
  if (error instanceof WazzaEngine.APIError) {
    console.error('API Error:', {
      code: error.code,
      message: error.message,
      status: error.status,
      requestId: error.requestId
    });

    // Handle specific error codes
    switch (error.code) {
      case 'INSUFFICIENT_CREDITS':
        // Redirect to billing page
        break;
      case 'INVALID_PROMPT':
        // Show user-friendly message
        break;
      case 'RATE_LIMIT_EXCEEDED':
        // Implement retry logic
        break;
      default:
        // Generic error handling
    }
  } else {
    console.error('Unexpected error:', error);
  }
}

Implementing Retry Logic

async function generateWithRetry(options, maxRetries = 3) {
  let lastError;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await wazza.generate(options);
      return response;
    } catch (error) {
      lastError = error;

      // Don't retry client errors (4xx)
      if (error.status >= 400 && error.status < 500) {
        if (error.code === 'RATE_LIMIT_EXCEEDED') {
          // Exponential backoff for rate limits
          const delay = Math.min(1000 * Math.pow(2, attempt), 30000);
          console.log(`Rate limited, waiting ${delay}ms...`);
          await sleep(delay);
          continue;
        }
        // Don't retry other 4xx errors
        throw error;
      }

      // Retry server errors (5xx)
      if (attempt < maxRetries) {
        const delay = 1000 * attempt;
        console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
        await sleep(delay);
      }
    }
  }

  throw lastError;
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Usage
try {
  const response = await generateWithRetry({
    provider: 'openai',
    model: 'sora-2-pro',
    prompt: 'A beautiful landscape'
  });
} catch (error) {
  console.error('All retries failed:', error);
}

Provider Fallback

async function generateWithFallback(prompt) {
  // Try providers in priority order
  const providers = [
    { provider: 'openai', model: 'sora-2-pro' },
    { provider: 'google-gemini', model: 'veo-3.1' },
    { provider: 'runway', model: 'gen4_turbo' }
  ];

  for (const config of providers) {
    try {
      console.log(`Trying ${config.provider}...`);
      const response = await wazza.generate({
        ...config,
        prompt
      });
      return response;
    } catch (error) {
      console.error(`${config.provider} failed:, error.message`);
      // Continue to next provider
    }
  }

  throw new Error('All providers failed');
}

// Usage
try {
  const response = await generateWithFallback(
    'A cinematic video of a sunset'
  );
  console.log('Success with:', response.metadata.provider);
} catch (error) {
  console.error('All providers exhausted:', error);
}

Debugging Tips

1. Use Request IDs

Every response includes a unique requestId. Include this when contacting support:

x-request-id: req_abc123def456

2. Enable Debug Logging

const wazza = new WazzaEngine({
  apiKey: process.env.WAZZA_API_KEY,
  debug: true // Enables detailed logging
});

3. Check API Status

Monitor real-time API status at status.wazza.ai

4. Test in Staging

Use staging environment for testing:

const wazza = new WazzaEngine({
  apiKey: process.env.WAZZA_API_KEY,
  baseURL: 'https://api.wazza.ai'
});

Best Practices

1. Always Handle Errors

  • Wrap all API calls in try-catch blocks
  • Don't expose raw error messages to end users
  • Log errors with context for debugging

2. Implement Retry Logic

  • Retry 5xx errors with exponential backoff
  • Don't retry 4xx errors (except rate limits)
  • Set maximum retry attempts (3-5 recommended)

3. Handle Rate Limits Gracefully

  • Check rate limit headers in responses
  • Implement client-side rate limiting
  • Use exponential backoff for 429 errors

4. Monitor Error Rates

  • Track error rates and types in your application
  • Set up alerts for elevated error rates
  • Review error logs regularly