Skip to main content
OnDB SDKs provide specific error types for comprehensive error handling.

Error Types

Error TypeDescription
OnDBErrorBase error class for all SDK errors
ValidationErrorData validation failed
TransactionErrorBlockchain transaction failed
PaymentRequiredErrorPayment required (HTTP 402)
PaymentVerificationErrorPayment verification failed

Basic Error Handling

TypeScript
import {
  OnDBError,
  TransactionError,
  ValidationError,
  PaymentRequiredError,
  PaymentVerificationError,
} from '@ondb/sdk';

try {
  await client.store(
    { collection: 'test', data: [{ test: 'data' }] },
    paymentCallback
  );
} catch (error) {
  if (error instanceof ValidationError) {
    console.log('Validation failed:', error.message);
    console.log('Details:', error.details);
  } else if (error instanceof TransactionError) {
    console.log('Transaction failed:', error.transactionId);
  } else if (error instanceof PaymentRequiredError) {
    console.log('Payment required');
    console.log('Error:', error.paymentRequired.error);
    console.log('Options:', error.paymentRequired.accepts.length);
  } else if (error instanceof PaymentVerificationError) {
    console.log('Payment verification failed:', error.txHash);
  } else if (error instanceof OnDBError) {
    console.log('OnDB error:', error.code, error.statusCode);
  }
}

Validation Errors

Thrown when data validation fails:
TypeScript
try {
  await client.store(
    { collection: 'users', data: [{ email: 'invalid-email', age: -5 }] },
    paymentCallback, true
  );
} catch (error) {
  if (error instanceof ValidationError) {
    console.log('Validation errors:');
    Object.entries(error.details).forEach(([field, messages]) => {
      console.log(`  ${field}: ${messages.join(', ')}`);
    });
  }
}

Payment Required Handling

Handle payment required errors:
TypeScript
try {
  const result = await client.queryBuilder()
    .collection('premium_data')
    .selectAll()
    .execute();
} catch (error) {
  if (error instanceof PaymentRequiredError) {
    const paymentInfo = error.paymentRequired;
    console.log('Payment required');
    console.log('Error:', paymentInfo.error);
    console.log('Payment options:', paymentInfo.accepts.length);

    // Handle payment flow
    const txHash = await processPayment(quote);
    // Retry with payment proof
  }
}

Retry Pattern with Exponential Backoff

TypeScript
async function storeWithRetry(
  data: any,
  maxRetries: number = 3,
  delay: number = 1000
) {
  let lastError: Error;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await client.store(data, paymentCallback, true);
    } catch (error) {
      lastError = error;

      // Don't retry validation errors
      if (error instanceof ValidationError) {
        throw error;
      }

      // Don't retry payment required (needs user action)
      if (error instanceof PaymentRequiredError) {
        throw error;
      }

      // Retry transient errors
      if (error instanceof TransactionError || error instanceof OnDBError) {
        console.log(`Attempt ${attempt} failed, retrying in ${delay}ms...`);
        await new Promise(resolve => setTimeout(resolve, delay));
        delay *= 2; // Exponential backoff
        continue;
      }

      throw error;
    }
  }

  throw lastError;
}

Error Logging

TypeScript
function logError(error: Error) {
  const timestamp = new Date().toISOString();

  if (error instanceof ValidationError) {
    console.error(`[${timestamp}] Validation Error:`, {
      message: error.message,
      details: error.details,
      code: error.code
    });
  } else if (error instanceof TransactionError) {
    console.error(`[${timestamp}] Transaction Error:`, {
      message: error.message,
      transactionId: error.transactionId
    });
  } else if (error instanceof PaymentRequiredError) {
    console.error(`[${timestamp}] Payment Required:`, {
      error: error.paymentRequired.error,
      options: error.paymentRequired.accepts.length
    });
  } else {
    console.error(`[${timestamp}] Error:`, error.message);
  }
}

Next Steps

API Reference

Complete SDK reference

Best Practices

Recommended patterns