Course contentsShow
← Node.js
Lesson 1668 of 1,98015. Logging, Observability, and MetricsFree lesson

Error Wrapping and Contextual Stacks

Enhance error reporting by appending high-level business context to low-level stack traces.

Error Wrapping and Contextual Stacks

In this lesson, you will learn how to preserve the diagnostic trail of a failure by wrapping low-level technical errors with high-level business context.

When an application fails—for example, when a database driver throws a ConnectionTimeoutError—the raw stack trace explains where in the code the connection failed, but it lacks the why from a business perspective. Was this happening during a user login, a bulk data export, or a scheduled report generation? By the time a log reaches your aggregation service, that intent is often lost.

To solve this, we use Error Wrapping. Instead of simply logging the original error or re-throwing it, we create a new error that contains the original as a "cause." This allows us to append human-readable metadata while keeping the original stack trace intact for technical debugging.

Implementing Contextual Wrappers

Consider a scenario where a database query fails. Rather than throwing the generic driver error, we catch it and wrap it with the current operation's context:

async function processUserPayment(userId, amount) {
  try {
    await database.charge(userId, amount);
  } catch (err) {
    // We wrap the raw error with high-level business context
    const wrappedError = new Error(`Failed to process payment for user ${userId}`);
    wrappedError.cause = err; // Modern JS preserves the original stack via 'cause'
    throw wrappedError;
  }
}

When this error is caught by your global logger, the resulting log output will contain the high-level description (Failed to process payment...) followed by the original technical stack trace (ConnectionTimeoutError: Connection failed at ...).

By following this pattern, you bridge the gap between "what broke in the runtime" and "what failed in the user journey." You maintain the precision of the underlying exception while providing the immediate clarity needed by operations teams to identify which part of the business workflow was interrupted. This avoids the "mystery log" problem, where you have a technical stack trace but no idea which user or system action triggered it.

Key Takeaway: Always wrap low-level errors with high-level business intent to ensure your logs tell both the story of the code execution and the story of the user operation.