@satyajit_me/retry-handler
v1.0.1
Published
Automatic retry logic with exponential backoff and configurable strategies
Maintainers
Readme
Retry Handler
Automatic retry logic with exponential backoff and configurable strategies.
Installation
npm install retry-handlerQuick Start
import { retry, withRetry } from 'retry-handler';
// Retry an async function
const result = await retry(async () => {
return await fetchData();
});
// Wrap a function with retry logic
const fetchWithRetry = withRetry(fetchData, { maxRetries: 5 });
await fetchWithRetry();API
retry(fn, options)
await retry(async (attempt) => {
console.log(`Attempt ${attempt + 1}`);
return await apiCall();
}, {
maxRetries: 3, // Number of retries
baseDelay: 1000, // Initial delay (ms)
maxDelay: 30000, // Maximum delay (ms)
factor: 2, // Exponential factor
jitter: true, // Add randomization
jitterFactor: 0.2, // Jitter amount (±20%)
timeout: 5000, // Per-attempt timeout
shouldRetry: (err) => true, // Retry condition
onRetry: (err, attempt, delay) => {} // Hook
});Backoff Strategies
// Exponential (default)
retry(fn, { factor: 2 }) // 1s, 2s, 4s, 8s...
// Linear
retryLinear(fn, { delay: 1000 }) // 1s, 2s, 3s, 4s...
// Fixed (no backoff)
retryFixed(fn, { delay: 1000 }) // 1s, 1s, 1s...withRetry(fn, options)
Create a retryable version of any function:
const robustFetch = withRetry(fetch, { maxRetries: 3 });
await robustFetch('/api/data');Retry Conditions
import { retryConditions } from 'retry-handler';
// Retry on network errors
retry(fn, { shouldRetry: retryConditions.networkError });
// Retry on specific HTTP status codes
retry(fn, { shouldRetry: retryConditions.httpStatus([500, 502, 503]) });
// Always/never retry
retry(fn, { shouldRetry: retryConditions.always });
retry(fn, { shouldRetry: retryConditions.never });RetryableOperation
For more control:
const op = new RetryableOperation(fn, options);
try {
await op.execute();
} catch (error) {
console.log('Failed after', op.getAttempts(), 'retries');
console.log('Errors:', op.getErrors());
}
// Abort in-progress operation
op.abort();License
MIT
