TypeScript Retry Decorator

2.5.4 · active · verified Tue Apr 21

The `typescript-retry-decorator` library provides a simple, zero-dependency decorator for adding retry logic to TypeScript functions, inspired by Spring-Retry. It supports both synchronous and asynchronous (Promise-returning) functions, making it suitable for Node.js and modern browser environments. The current stable version is 2.5.4, with releases occurring periodically, often addressing compatibility with newer TypeScript features or Node.js module systems, as seen in recent 2.5.x patches. Its key differentiators include its lightweight nature (no external dependencies), comprehensive test coverage, and support for both legacy and TypeScript 5+ standard decorators, offering various backoff policies (fixed, exponential with jitter) and custom error handling for retry conditions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates applying the `@Retry` decorator to an asynchronous method, configured with exponential backoff and custom retry conditions for transient errors.

import { Retry, ExponentialBackOffPolicy } from 'typescript-retry-decorator';

// Simulate an external service call that fails a few times
let callCount = 0;
async function unreliableServiceCall(data: string): Promise<string> {
  callCount++;
  if (callCount < 3) { // Fail for the first 2 calls
    console.log(`Attempt ${callCount}: Service call failed for data: ${data}`);
    throw new Error('Service temporarily unavailable');
  }
  console.log(`Attempt ${callCount}: Service call succeeded for data: ${data}`);
  return `Processed: ${data}`;
}

class MyService {
  @Retry({
    maxAttempts: 5,
    backOff: 100, // initial backoff 100ms
    backOffPolicy: ExponentialBackOffPolicy,
    exponentialOption: { multiplier: 2, maxInterval: 1000 }, // Intervals: 100, 200, 400, 800, 1000, 1000...
    doRetry: (e: any) => {
      console.log(`Checking error for retry: ${e.message}`);
      return e.message === 'Service temporarily unavailable';
    },
    value: [Error], // Retry on any Error class
    useOriginalError: true, // Throw original error if max attempts reached
    useConsoleLogger: true
  })
  async processData(input: string): Promise<string> {
    console.log(`Executing processData for input: ${input}`);
    return unreliableServiceCall(input);
  }
}

async function runExample() {
  const service = new MyService();
  try {
    const result = await service.processData('example-data');
    console.log(`Final Result: ${result}`);
  } catch (error: any) {
    console.error(`Operation failed after retries: ${error.message}`);
  } finally {
    callCount = 0; // Reset for potential re-runs
  }
}

runExample();

view raw JSON →