Skip to main content

Overview

Stringboot is designed to fail gracefully, but it’s important to handle errors properly to provide the best user experience. This guide covers error handling patterns for all platforms.

Common Error Scenarios

When it happens: No internet connection or server unreachableSDK behavior: Automatically falls back to cached dataUser impact: No visible error if data is cachedAction needed: Inform users that content may be outdated
When it happens: String key doesn’t exist in any languageSDK behavior: Returns "??key??" formatUser impact: Visible placeholder textAction needed: Provide fallback text or log for debugging
When it happens: Invalid or expired API tokenSDK behavior: Logs error, uses cached data, disables syncUser impact: App works with cached data but won’t updateAction needed: Validate API token configuration
When it happens: Too many requests to serverSDK behavior: Automatic retry with exponential backoff (max 3 attempts)User impact: Slight delay in updatesAction needed: None - handled automatically
When it happens: Server-side issuesSDK behavior: Retry with backoff, fall back to cacheUser impact: May use slightly outdated contentAction needed: Check server status, report if persistent

Platform-Specific Error Handling

  • Web SDK
  • Android SDK
  • iOS SDK

Initialization Errors

try {
  await StringBoot.initialize({
    apiToken: 'your-token',
    baseUrl: 'https://api.stringboot.com',
    defaultLanguage: 'en'
  });
  console.log('✓ SDK initialized successfully');
} catch (error) {
  console.error('✗ Initialization failed:', error);
  // Show error to user or use fallback
}

Operation Errors

const syncBtn = document.getElementById('syncBtn');

syncBtn.addEventListener('click', async () => {
  syncBtn.disabled = true;
  syncBtn.textContent = 'Syncing...';

  try {
    await StringBoot.syncNow();
    showStatus('success', '✓ Sync completed');
  } catch (error) {
    showStatus('error', `✗ Sync failed: ${error.message}`);
    console.error('Sync error:', error);
  } finally {
    syncBtn.disabled = false;
    syncBtn.textContent = 'Sync Now';
  }
});

React Error Handling

import { useStringBoot } from '@stringboot/web-sdk/react';

function App() {
  const { initialized, error } = useStringBoot({
    apiToken: 'token',
    baseUrl: 'url',
  });

  if (error) {
    return (
      <div className="error">
        <h1>Error initializing SDK</h1>
        <p>{error}</p>
        <button onClick={() => window.location.reload()}>
          Retry
        </button>
      </div>
    );
  }

  if (!initialized) {
    return <div>Loading...</div>;
  }

  return <MainContent />;
}

Missing String Handling

const text = await StringBoot.get('unknown_key');

if (text.startsWith('??') && text.endsWith('??')) {
  // String not found, use fallback
  document.getElementById('text').textContent = 'Default Text';
} else {
  document.getElementById('text').textContent = text;
}

Network-Specific Errors

try {
  await StringBoot.syncNow();
} catch (error) {
  if (error.message.includes('Network')) {
    console.log('Network error, using cached values');
    showStatus('warning', 'Offline - using cached content');
  } else if (error.message.includes('timeout')) {
    console.log('Request timed out, retrying...');
    // Implement retry logic
  } else {
    console.error('Unexpected error:', error);
  }
}

HTTP Status Code Handling

The SDK automatically handles these HTTP status codes:
Status CodeMeaningSDK ResponseRetry?
200SuccessParse and cache dataN/A
304Not ModifiedUse existing cacheNo
401UnauthorizedLog error, use cacheNo
403ForbiddenLog error, use cacheNo
404Not FoundLanguage doesn’t existNo
429Rate LimitedExponential backoffYes (3x)
500-599Server ErrorRetry with backoffYes (3x)
Network ErrorNo connectionUse cache immediatelyNo

Best Practices

Always Use try/catch

Wrap all SDK operations in try/catch blocks to handle unexpected errors

Provide Fallbacks

Always have fallback text for missing strings

Show Loading States

Indicate when operations are in progress

Log Errors

Log errors for debugging and monitoring

Don't Block UI

Never block the main thread waiting for network operations

Test Offline

Test your app in airplane mode to ensure offline functionality

Handle Edge Cases

Account for missing strings, slow networks, and API errors

Monitor in Production

Use error tracking to identify issues in production

Error Logging

Enable Debug Logging

// Enable debug mode
await StringBoot.initialize({
  apiToken: 'token',
  baseUrl: 'url',
  debug: true  // Logs all operations to console
});

Production Error Tracking

Integrate with your error tracking service:
try {
  await StringBoot.syncNow();
} catch (error) {
  // Log to your error tracking service
  Sentry.captureException(error, {
    tags: {
      component: 'stringboot',
      operation: 'sync'
    }
  });

  // Still handle gracefully for user
  console.error('Sync failed, using cached data');
}

Testing Error Scenarios

Simulate Network Errors

  • Web
  • Android
  • iOS
// Test offline behavior
// 1. Open DevTools → Network tab
// 2. Select "Offline" from throttling dropdown
// 3. Verify app still works with cached data

// Or use navigator.onLine
if (!navigator.onLine) {
  showStatus('warning', 'You are offline');
}

Test Missing Strings

Create test cases for missing keys:
// Test missing string handling
const missingKey = await StringBoot.get('this_key_does_not_exist');
console.assert(
  missingKey === '??this_key_does_not_exist??',
  'Missing strings should return ??key?? format'
);

Next Steps