Error Handling

Handle API errors gracefully in your application

Basic Error Handling

import { VedikaClient, VedikaAPIError } from '@vedika-io/sdk';

const client = new VedikaClient({ apiKey: process.env.VEDIKA_API_KEY });

try {
  const chart = await client.post('/v2/astrology/birth-chart', {
    datetime: '1990-05-15T10:30:00',
    latitude: 28.6139,
    longitude: 77.2090,
    timezone: '+05:30'
  });
} catch (error) {
  if (error instanceof VedikaAPIError) {
    console.error('API Error:', error.message);
    console.error('Error Code:', error.code);
    console.error('Status:', error.statusCode);
  } else {
    console.error('Unexpected error:', error);
  }
}

Error Codes Reference

Code Status Description Action
INVALID_API_KEY 401 API key is invalid or missing Check API key configuration
EXPIRED_API_KEY 401 API key has expired Regenerate key in dashboard
INSUFFICIENT_BALANCE 402 Not enough credits for request Add credits to account
RATE_LIMIT_EXCEEDED 429 Too many requests Wait and retry with backoff
INVALID_PARAMETERS 400 Invalid request parameters Check parameter values
INVALID_DATE 400 Invalid date format Use ISO 8601 format
INVALID_COORDINATES 400 Latitude/longitude out of range Lat: -90 to 90, Lng: -180 to 180
SERVICE_UNAVAILABLE 503 Service temporarily unavailable Retry with exponential backoff
TIMEOUT 504 Request timed out Retry or increase timeout

VedikaAPIError Object

class VedikaAPIError extends Error {
  statusCode?: number;          // HTTP status code
  code?: string;                // Machine-readable code from the error body (e.g., 'INSUFFICIENT_BALANCE')
  message: string;              // Human-readable message
  body?: Record<string, any>;   // Parsed JSON error body, when the server sent one
}

// Subclasses, all exported from '@vedika-io/sdk'. Each extends VedikaAPIError:
//   AuthenticationError (401)
//   InsufficientCreditsError (402)   required, available, deficit (USD), purchaseUrl
//   SubscriptionExpiredError (402)
//   ValidationError (422)
//   RateLimitError (429)             retryAfter (seconds), limits
//   DailyLimitExceededError (429)    extends RateLimitError; upgradeUrl, usage
//   TimeoutError, ServerError (5xx), NetworkError

// Example error object
// {
//   name: 'RateLimitError',
//   code: 'RATE_LIMIT_EXCEEDED',
//   statusCode: 429,
//   message: 'Rate limit exceeded',
//   retryAfter: 60
// }

Handle Specific Errors

import {
  VedikaClient,
  VedikaAPIError,
  AuthenticationError,
  InsufficientCreditsError,
  SubscriptionExpiredError,
  DailyLimitExceededError,
  RateLimitError,
  ValidationError,
  TimeoutError,
  ServerError,
  NetworkError
} from '@vedika-io/sdk';

const client = new VedikaClient({ apiKey: process.env.VEDIKA_API_KEY });

async function fetchChart(birthDetails) {
  try {
    return await client.post('/v2/astrology/birth-chart', birthDetails);
  } catch (error) {
    if (!(error instanceof VedikaAPIError)) {
      throw error;  // Re-throw unexpected errors
    }

    if (error instanceof AuthenticationError) {
      // Redirect to settings or show API key error
      console.error('Authentication failed. Please check your API key.');
      throw new Error('Please configure your API key');
    }

    if (error instanceof SubscriptionExpiredError) {
      console.error('Subscription expired.');
      throw new Error('Please renew your subscription to continue');
    }

    if (error instanceof InsufficientCreditsError) {
      // Redirect to billing or show upgrade prompt
      console.error(`Wallet short by $${error.deficit}. Add funds at ${error.purchaseUrl}`);
      throw new Error('Please add credits to continue');
    }

    if (error instanceof DailyLimitExceededError) {
      // The daily allowance is used up; retrying today will not help
      console.error('Daily limit reached. Upgrade at', error.upgradeUrl);
      throw new Error('Daily limit reached. Please try again tomorrow.');
    }

    if (error instanceof RateLimitError) {
      // Show rate limit message with retry time
      const waitTime = error.retryAfter || 60;
      console.error(`Rate limited. Retry in ${waitTime} seconds.`);
      throw new Error(`Too many requests. Please wait ${waitTime} seconds.`);
    }

    if (error instanceof ValidationError || error.statusCode === 400) {
      // Show input error; error.code and error.body say which field
      console.error('Invalid input:', error.code, error.body);
      throw new Error('Please check the date and location you entered');
    }

    if (error instanceof ServerError || error instanceof TimeoutError || error instanceof NetworkError) {
      // Show temporary error, maybe retry
      console.error('Service temporarily unavailable');
      throw new Error('Service is temporarily unavailable. Please try again.');
    }

    console.error('Unexpected API error:', error.code);
    throw new Error('An unexpected error occurred. Please try again.');
  }
}

Automatic Retries

// SDK has built-in retry logic
const client = new VedikaClient({
  apiKey: process.env.VEDIKA_API_KEY,
  maxRetries: 3,           // Retry up to 3 times (default)
  timeout: 30000           // 30 second timeout (default is 60000)
});

// Retries wait 1s, 2s, 4s (capped at 8s) and happen for:
// - Network errors and timeouts, on requests that are safe to repeat
// - 502/503/504 server errors, on requests that are safe to repeat
// - 429 RATE_LIMIT_EXCEEDED (waits the retryAfter the API sends, up to 30 seconds)
//
// "Safe to repeat" means a GET, or a POST that carries an Idempotency-Key.
// A billable POST without a key is never resent after a timeout or 5xx,
// because the first attempt may already have been charged.
//
// NOT retried:
// - 4xx client errors (invalid params, auth errors, insufficient balance)
// - 429 DAILY_LIMIT_EXCEEDED and PLAN_LIMIT_EXCEEDED

Custom Retry Logic

import {
  RateLimitError,
  DailyLimitExceededError,
  ServerError,
  TimeoutError,
  NetworkError
} from '@vedika-io/sdk';

function isRetryable(error) {
  // A used-up daily allowance does not come back by waiting a few seconds
  if (error instanceof DailyLimitExceededError) return false;
  return error instanceof RateLimitError ||
    error instanceof ServerError ||
    error instanceof TimeoutError ||
    error instanceof NetworkError;
}

async function withRetry(fn, options = {}) {
  const {
    maxRetries = 3,
    baseDelay = 1000,
    maxDelay = 30000
  } = options;

  let lastError;

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;

      // Don't retry non-retryable errors
      if (!isRetryable(error)) {
        throw error;
      }

      // Don't retry on last attempt
      if (attempt === maxRetries) {
        break;
      }

      // Calculate delay with exponential backoff
      let delay = baseDelay * Math.pow(2, attempt);

      // Respect the retryAfter the API sends for rate limits
      if (error.retryAfter) {
        delay = error.retryAfter * 1000;
      }

      // Cap the delay
      delay = Math.min(delay, maxDelay);

      console.log(`Retry ${attempt + 1}/${maxRetries} in ${delay}ms...`);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }

  throw lastError;
}

// Usage (create the client with maxRetries: 0 if you only want this loop to retry)
const chart = await withRetry(
  () => client.post('/v2/astrology/birth-chart', birthDetails),
  { maxRetries: 3, baseDelay: 2000 }
);

Validate Before Request

// Local helper; the SDK does not ship a validator

function validateInput(birthDetails) {
  const errors = [];

  // Date validation
  const date = new Date(birthDetails.datetime);
  if (isNaN(date.getTime())) {
    errors.push('Invalid date format. Use ISO 8601 (YYYY-MM-DDTHH:mm:ss)');
  }

  // Latitude validation
  if (birthDetails.latitude < -90 || birthDetails.latitude > 90) {
    errors.push('Latitude must be between -90 and 90');
  }

  // Longitude validation
  if (birthDetails.longitude < -180 || birthDetails.longitude > 180) {
    errors.push('Longitude must be between -180 and 180');
  }

  // Future date check
  if (date > new Date()) {
    errors.push('Birth date cannot be in the future');
  }

  return errors;
}

// Usage
const birthDetails = {
  datetime: '1990-05-15T10:30:00',
  latitude: 28.6139,
  longitude: 77.2090,
  timezone: '+05:30'
};

const errors = validateInput(birthDetails);
if (errors.length > 0) {
  throw new Error(`Validation errors: ${errors.join('; ')}`);
}

// Proceed with API call
const chart = await client.post('/v2/astrology/birth-chart', birthDetails);

Global Error Handler

// Create a wrapper with global error handling
class VedikaService {
  constructor(apiKey) {
    this.client = new VedikaClient({ apiKey });
    this.onError = null;  // Error callback
  }

  setErrorHandler(handler) {
    this.onError = handler;
  }

  async execute(method, call, params) {
    try {
      return await call();
    } catch (error) {
      // Log error
      console.error(`Vedika API Error [${method}]:`, error);

      // Track error (e.g., Sentry)
      if (typeof Sentry !== 'undefined') {
        Sentry.captureException(error, {
          tags: { api: 'vedika', method },
          extra: { params }
        });
      }

      // Call error handler
      if (this.onError) {
        this.onError(error, method, params);
      }

      throw error;
    }
  }

  birthChart(params) {
    return this.execute('birthChart', () => this.client.post('/v2/astrology/birth-chart', params), params);
  }

  panchang(params) {
    return this.execute('panchang', () => this.client.get('/v2/astrology/panchang', params), params);
  }

  // ... other methods
}

// Usage
const service = new VedikaService(process.env.VEDIKA_API_KEY);

service.setErrorHandler((error, method, params) => {
  // Show user-friendly toast notification
  showToast({
    type: 'error',
    message: getErrorMessage(error)
  });
});

function getErrorMessage(error) {
  const messages = {
    'INSUFFICIENT_BALANCE': 'Please add credits to continue using the service.',
    'RATE_LIMIT_EXCEEDED': 'Too many requests. Please slow down.',
    'SERVICE_UNAVAILABLE': 'Service temporarily unavailable. Please try again.'
  };
  return messages[error.code] || 'An error occurred. Please try again.';
}

Related Topics