Course contentsShow
← JavaScript
Lesson 1166 of 2,72326. Error HandlingFree lesson

Wrapping and Rethrowing Errors

Learn to catch errors, add context by wrapping them in new errors, and rethrow for further handling.

Wrapping and Rethrowing Errors

You'll learn how to catch errors, add helpful context around them, and pass them up the call stack for better debugging.

The Core Idea

Sometimes you catch an error at a low level in your code, but you don't have enough information to handle it properly there. Or you want to add context about where or why the error occurred before letting it bubble up. Wrapping and rethrowing means catching an error, creating a new error with additional information, and throwing that new error instead.

Think of it like a package delivery: if a warehouse worker finds a damaged item, they don't just pass it along silently. They wrap it with a note explaining when and where the damage was found, then send it up to management for the final decision.

Adding Context

When you catch an error, you can create a new error that includes both the original error details and new information:

function processUserData(userId) {
  try {
    // Some operation that might fail
    const data = fetchFromDatabase(userId);
    return data;
  } catch (originalError) {
    // Wrap the error with context
    const contextError = new Error(`Failed to process user ${userId}`);
    contextError.cause = originalError; // Preserve original error
    throw contextError; // Rethrow with added context
  }
}

Now when this error reaches the top level, you'll know which user caused the problem, not just that the database failed.

Why This Matters

Wrapping errors creates clearer error messages and debugging trails. The cause property (or custom properties) preserves the full error chain, so you never lose the original failure reason while adding application-specific context.

Key Takeaway: Wrap errors to add context about where or why they occurred, then rethrow them to let higher-level code make the final handling decision.