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.
The Flagdeck SDK can encounter several types of errors:
By default, the SDK will:
false
if none provided) for the flagdebug
mode is enabled)// Default behavior (no explicit error handling)
const isEnabled = await flagdeck.isEnabled('new-feature');
// If error occurs, returns false and logs error (in debug mode)
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 occurredflagKey
: The key of the flag being evaluated (if available)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();
}
}
The SDK provides specific error codes for different error scenarios:
Error Code | Description |
---|---|
NETWORK_ERROR | Failed to connect to the Flagdeck API |
AUTHENTICATION_ERROR | Invalid API key or authentication issue |
EVALUATION_ERROR | Error during flag evaluation logic |
TIMEOUT_ERROR | Request timeout occurred |
CONFIGURATION_ERROR | Invalid SDK configuration |
INVALID_FLAG_KEY | Invalid or missing flag key |
UNKNOWN_ERROR | Unidentified 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);
}
}
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:
For handling network errors gracefully, enable offline mode:
const flagdeck = new Flagdeck({
apiKey: 'your-api-key',
enableOfflineMode: true
});
With offline mode enabled:
See the Offline Mode documentation for more details.
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()
};
}
});
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
}
});
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>
);
}
Always Provide Default Values: Make sure your application has sensible defaults if flag evaluation fails
Use Try/Catch for Critical Features: Add explicit try/catch blocks around flag evaluations that are critical to your application
Implement a Global Error Handler: Configure the onError
handler to monitor and track errors
Monitor Error Rates: Set up monitoring for flag evaluation errors to identify issues early
Graceful Degradation: Design your application to work reasonably well even when flag evaluation fails
Offline Mode for Mobile: Always enable offline mode for mobile applications to handle intermittent connectivity
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.
Product
© 2025 Flagdeck. All rights reserved.