Course contentsShow
← JavaScript
Lesson 2093 of 2,72343. DecoratorsFree lesson

Retry Logic Decorators

Wrap methods with retry behavior that automatically attempts failed operations multiple times.

Retry Logic Decorators

What you'll learn: How to create decorators that automatically retry failed method calls a specified number of times before giving up.

The Core Idea

A retry logic decorator wraps a method so that if it throws an error or returns a rejected promise, the decorator automatically attempts to call it again—up to a maximum number of tries. This is incredibly useful for operations that might fail temporarily, like network requests, database queries, or any external service calls.

Think of it like a persistent friend trying to knock on a door: if no one answers the first time, they'll knock again a few more times before finally giving up.

Building a Retry Decorator

The decorator intercepts the original method, wraps it in retry logic, and handles failures gracefully:

function retry(maxAttempts = 3, delay = 1000) {
  return function(originalMethod, context) {
    return async function(...args) {
      let lastError;
      
      for (let attempt = 1; attempt <= maxAttempts; attempt++) {
        try {
          return await originalMethod.call(this, ...args);
        } catch (error) {
          lastError = error;
          if (attempt < maxAttempts) {
            await new Promise(resolve => setTimeout(resolve, delay));
          }
        }
      }
      
      throw new Error(`Failed after ${maxAttempts} attempts: ${lastError.message}`);
    };
  };
}

class ApiClient {
  @retry(3, 1000)
  async fetchData(url) {
    const response = await fetch(url);
    if (!response.ok) throw new Error('Network error');
    return response.json();
  }
}

The decorator tries the method up to three times with a 1-second pause between attempts. If all attempts fail, it throws a descriptive error.

Key Takeaway: Retry logic decorators make your code more resilient by automatically handling transient failures, transforming fragile operations into robust, self-healing ones without cluttering your method implementations with repetitive error-handling code.