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

Async Error Handling Decorators

Automatically wrap async methods in try-catch blocks to centralize error handling logic.

Async Error Handling Decorators

You'll learn how to create decorators that automatically wrap asynchronous methods in try-catch blocks, eliminating repetitive error handling code throughout your application.

The Core Idea

When working with async methods, you often need to wrap each one in a try-catch block to handle errors gracefully. This leads to duplicated boilerplate code across your class methods. An async error handling decorator centralizes this logic—you apply it once to any async method, and it automatically catches errors and handles them according to your application's needs.

Think of it like having a safety net installer who follows you around: instead of manually setting up a net under every tightrope you cross, you hire someone to do it automatically wherever you walk.

Basic Implementation

function catchErrors(errorHandler) {
  return function(target, context) {
    return async function(...args) {
      try {
        return await target.apply(this, args);
      } catch (error) {
        return errorHandler(error, context.name);
      }
    };
  };
}

class DataService {
  @catchErrors((err, method) => {
    console.error(`Error in ${method}:`, err.message);
    return null;
  })
  async fetchData(url) {
    const response = await fetch(url);
    return response.json();
  }
  
  @catchErrors((err, method) => {
    console.error(`Error in ${method}:`, err.message);
    return [];
  })
  async loadItems() {
    throw new Error('Network failure');
  }
}

const service = new DataService();
await service.loadItems(); // Logs error, returns []

Instead of wrapping every async method body in try-catch, you apply the decorator once and define how errors should be handled.

Key Takeaway: Async error handling decorators eliminate repetitive try-catch blocks by automatically wrapping async methods with centralized error handling logic, making your code cleaner and more maintainable.