Flagdeck
Pricing
Docs
Get Started

Docs

Docs


SDKs

  • JavaScript
    • Getting Started
    • Value Types
    • Evaluation Context
    • Configuration
    • Real Time Updates
    • Error Handling
    • Middleware
    • Offline Mode
    • API Reference
  • React

API Reference

  • Authentication
  • Flags
  • Environments
  • Projects

Error Handling

Properly handling errors in your feature flag system is essential for building resilient applications. This guide covers how to handle errors when using the Flagdeck JavaScript SDK.

Error Types

The Flagdeck SDK can encounter several types of errors:

  1. Network Errors - Connection failures when communicating with the Flagdeck API
  2. Authentication Errors - Issues with the API key or permissions
  3. Evaluation Errors - Problems during flag evaluation
  4. Configuration Errors - Improper SDK configuration
  5. Timeout Errors - Request timeouts

Default Error Behavior

By default, the SDK will:

  1. Return the default value (or false if none provided) for the flag
  2. Log the error to the console (if debug mode is enabled)
  3. Continue operating without crashing your application
// Default behavior (no explicit error handling)
const isEnabled = await flagdeck.isEnabled('new-feature');
// If error occurs, returns false and logs error (in debug mode)

Global Error Handler

You can configure a global error handler when initializing the SDK:

const flagdeck = new Flagdeck({
  apiKey: 'your-api-key',
  onError: (error, flagKey) => {
    console.error(`Error evaluating flag ${flagKey}:`, error);

    // Log to your error tracking system
    errorTracker.captureException(error, {
      tags: {
        flagKey,
        source: 'flagdeck'
      }
    });
  },
  defaultFlagValue: false // Value to use if evaluation fails
});

The onError handler receives:

  • error: The Error object that occurred
  • flagKey: The key of the flag being evaluated (if available)

Try/Catch Error Handling

For more specific handling, you can use try/catch blocks:

try {
  const result = await flagdeck.evaluateFlag('new-feature');
  // Use result
} catch (error) {
  // Handle error
  console.error('Failed to evaluate flag:', error);

  // You might want to implement specific fallback behavior
  if (error.code === 'NETWORK_ERROR') {
    // Handle network error specifically
    showOfflineMessage();
  }
}

Error Codes

The SDK provides specific error codes for different error scenarios:

Error CodeDescription
NETWORK_ERRORFailed to connect to the Flagdeck API
AUTHENTICATION_ERRORInvalid API key or authentication issue
EVALUATION_ERRORError during flag evaluation logic
TIMEOUT_ERRORRequest timeout occurred
CONFIGURATION_ERRORInvalid SDK configuration
INVALID_FLAG_KEYInvalid or missing flag key
UNKNOWN_ERRORUnidentified error

You can check these codes for more specific error handling:

try {
  const result = await flagdeck.evaluateFlag('new-feature');
} catch (error) {
  switch (error.code) {
    case 'NETWORK_ERROR':
      // Handle connectivity issues
      enableOfflineMode();
      break;

    case 'AUTHENTICATION_ERROR':
      // Handle authentication problems
      refreshApiKey();
      break;

    case 'TIMEOUT_ERROR':
      // Handle timeout
      showTimeoutMessage();
      break;

    default:
      // Handle other errors
      logGenericError(error);
  }
}

Default Values

One of the simplest ways to handle errors is to provide default values:

// Simple flag with default
const isEnabled = await flagdeck.isEnabled('new-feature', context, false);

// Complex configuration with default
const config = await flagdeck.getValue('api-config', context, {
  url: 'https://api.default.com',
  timeout: 5000,
  retries: 3
});

The default value is used when:

  • The flag doesn't exist
  • An error occurs during evaluation
  • The network request fails
  • The API returns an error response

Offline Mode

For handling network errors gracefully, enable offline mode:

const flagdeck = new Flagdeck({
  apiKey: 'your-api-key',
  enableOfflineMode: true
});

With offline mode enabled:

  1. When online, flag values are cached locally
  2. If a network error occurs, cached values are used
  3. The SDK gracefully degrades to using stored values

See the Offline Mode documentation for more details.

Middleware for Error Handling

You can implement middleware to centralize error handling:

flagdeck.use({
  name: 'ErrorHandlingMiddleware',
  onError: (error, flagKey) => {
    // Log error to monitoring service
    Sentry.captureException(error, {
      extra: { flagKey }
    });

    // Custom fallback behavior
    if (error.code === 'NETWORK_ERROR' && flagKey === 'critical-feature') {
      triggerEmergencyMode();
    }

    // You can also return a fallback value
    return {
      flagKey,
      value: determineFallbackValue(flagKey),
      source: 'error-middleware',
      reason: 'Fallback due to error',
      timestamp: Date.now()
    };
  }
});

Retry Behavior

The SDK automatically retries failed network requests. You can configure this behavior:

const flagdeck = new Flagdeck({
  apiKey: 'your-api-key',
  retryConfig: {
    attempts: 3,    // Maximum number of retry attempts
    delay: 1000,    // Initial delay in milliseconds
    maxDelay: 5000  // Maximum delay between retries
  }
});

Error Handling in React Components

Here's an example of handling flag evaluation errors in a React component:

import React, { useState, useEffect } from 'react';
import { flagdeck } from './flagdeck-client';

function FeatureComponent() {
  const [isEnabled, setIsEnabled] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function checkFeature() {
      try {
        setIsLoading(true);
        const enabled = await flagdeck.isEnabled('new-feature');
        setIsEnabled(enabled);
        setError(null);
      } catch (err) {
        console.error('Error checking feature flag:', err);
        setError(err);
        // Default to false on error
        setIsEnabled(false);
      } finally {
        setIsLoading(false);
      }
    }

    checkFeature();
  }, []);

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

  if (error) {
    return (
      <div>
        <p>There was an error checking this feature.</p>
        <p>Using default experience.</p>
      </div>
    );
  }

  return (
    <div>
      {isEnabled ? (
        <NewFeatureComponent />
      ) : (
        <DefaultComponent />
      )}
    </div>
  );
}

Best Practices

  1. Always Provide Default Values: Make sure your application has sensible defaults if flag evaluation fails

  2. Use Try/Catch for Critical Features: Add explicit try/catch blocks around flag evaluations that are critical to your application

  3. Implement a Global Error Handler: Configure the onError handler to monitor and track errors

  4. Monitor Error Rates: Set up monitoring for flag evaluation errors to identify issues early

  5. Graceful Degradation: Design your application to work reasonably well even when flag evaluation fails

  6. Offline Mode for Mobile: Always enable offline mode for mobile applications to handle intermittent connectivity

  7. Test Error Scenarios: Deliberately test how your application behaves when flag evaluation fails

Start using Flagdeck today

Simple feature flag management for modern development teams.

Get Started
Flagdeck

Modern feature flag management platform to help you deploy with confidence.

Product

FeaturesPricingDocumentation

© 2025 Flagdeck. All rights reserved.