Course contentsShow
← Software Engineering
Lesson 1091 of 1,93333. Error Handling and ResilienceFree lesson

Error Context and Propagation

Preserve context when propagating errors through layers to enable effective debugging and handling.

Error Context and Propagation

You'll learn: How to preserve and enrich error information as it travels through your application layers to make debugging and handling effective.

The Problem with Naked Errors

When an error occurs deep in your codebase—say, a database connection fails—and you simply throw or return that raw error upward, the caller loses critical context. Where did this fail? What operation was being attempted? What were the input parameters?

It's like receiving a text that just says "Error" with no sender, timestamp, or conversation history.

Enriching Errors as They Propagate

Each layer of your application should wrap or annotate errors as they bubble up, adding context relevant to that layer:

# Deep layer: database
def fetch_user(user_id):
    try:
        return db.query("SELECT * FROM users WHERE id = ?", user_id)
    except DatabaseError as e:
        raise UserRepositoryError(f"Failed to fetch user {user_id}") from e

# Middle layer: business logic
def get_user_profile(user_id):
    try:
        return fetch_user(user_id)
    except UserRepositoryError as e:
        raise ProfileServiceError(f"Cannot load profile for user {user_id}") from e

Notice how each layer adds its own context while preserving the original error with from e (or your language's equivalent chaining mechanism).

What Context to Preserve

  • Operation being performed: "fetching user", "processing payment"
  • Relevant identifiers: user IDs, transaction IDs, request IDs
  • Input parameters (sanitized of sensitive data)
  • Original error: always chain/wrap, never discard
  • Timestamps and correlation IDs for distributed systems

The Debugging Payoff

With proper context propagation, your logs tell a story: "ProfileServiceError: Cannot load profile for user 42 → UserRepositoryError: Failed to fetch user 42 → DatabaseError: Connection timeout." You instantly know the flow and failure point.

Key Takeaway: Always add layer-specific context when propagating errors upward, and preserve the original error chain—future you (and your teammates) will thank you during 3 AM incidents.