error-handling-pattern-2-error-propagation-and-chains

error-handling-pattern-2-error-propagation-and-chains is a cursor rule for Cursor from PaulJPhilp/EffectPatterns. It costs 2,091 tokens per session, scanned A, original, MIT.

An error-handling pattern that carries useful context through a chain of operations so the right layer can handle the problem.

In plain words
What is it for?
Use it to define and pass database, network, validation, and business-logic errors through TypeScript Effect programs.
Why use it?
It prevents errors from losing details such as the failed database query, network request, or business operation.

Cursor rule for Cursor

Written for Cursor: a Cursor rule (.mdc).

Good fit Use it to define and pass database, network, validation, and business-logic errors through TypeScript Effect programs.

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/pauljphilp/effectpatterns/error-handling-pattern-2-error-propagation-and-chains
Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

Clone the repo
git clone --depth 1 https://github.com/PaulJPhilp/EffectPatterns

Made for: Cursor.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for error-handling-pattern-2-error-propagation-and-chains

README.md
[![agentmods](https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/error-handling-pattern-2-error-propagation-and-chains.svg)](https://agentmods.dev/rules/pauljphilp/effectpatterns/error-handling-pattern-2-error-propagation-and-chains)
Your own site
<a href="https://agentmods.dev/rules/pauljphilp/effectpatterns/error-handling-pattern-2-error-propagation-and-chains"><img src="https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/error-handling-pattern-2-error-propagation-and-chains.svg" alt="Measured on agentmods" height="20"></a>
Per session 2,091 This file is loaded in full into every session.
When invoked 2,091 The same file — it is already loaded in full.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.02091 $0.02091
Opus 5 $0.01045 $0.01045
Sonnet 5 $0.00418 $0.00418
Haiku 4.5 $0.00209 $0.00209

Measured 4d ago against content hash bcd7bbb5ca24, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-07, from the pricing page.

Security

Grade A, and why

error-handling-pattern-2-error-propagation-and-chains scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 4d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

content/published/rules/cursor/error-handling-pattern-2-error-propagation-and-chains.mdc · 351 lines

How it starts

The opening of the file, as written. The whole thing — 351 lines — stays where its author put it; the contents beside it link to each section on GitHub.

description: Use error propagation to preserve context through effect chains, enabling debugging and recovery at the right abstraction level. globs: "**/*.ts" alwaysApply: true

Error Handling Pattern 2: Error Propagation and Chains

Rule: Use error propagation to preserve context through effect chains, enabling debugging and recovery at the right abstraction level.

Example

This example demonstrates error propagation with context.

import { Effect, Data, Cause } from "effect";

// Domain-specific errors with context
class DatabaseError extends Data.TaggedError("DatabaseError")<{
  query: string;
  parameters: unknown[];
  cause: Error;
}> {}

class NetworkError extends Data.TaggedError("NetworkError")<{
  endpoint: string;
  method: string;
  statusCode?: number;
  cause: Error;
}> {}

class ValidationError extends Data.TaggedError("ValidationError")<{
  field: string;
  value: unknown;
  reason: string;
}> {}

class BusinessLogicError extends Data.TaggedError("BusinessLogicError")<{
  operation: string;
  context: Record<string, unknown>;
  originalError: Error;
}> {}

const program = Effect.gen(function* () {
  console.log(`\n[ERROR PROPAGATION] Error chains with context\n`);

  // Example 1: Simple error propagation
  console.log(`[1] Error propagation through layers:\n`);

  const lowLevelOperation = Effect.gen(function* () {
    yield* Effect.log(`[LAYER 1] Low-level operation starting`);

    yield* Effect.fail(new Error("File not found"));
  });

  const midLevelOperation = lowLevelOperation.pipe(
    Effect.mapError((error) =>
      new DatabaseError({
        query: "SELECT * FROM users",
        parameters: ["id=123"],
        cause: error instanceof Error ? error : new Error(String(error)),
      })
    )
  );

  const highLevelOperation = midLevelOperation.pipe(
    Effect.catchTag("DatabaseError", (dbError) =>
      Effect.gen(function* () {
        yield* Effect.log(`[LAYER 3] Caught database error`);
        yield* Effect.log(`[LAYER 3]   Query: ${dbError.query}`);
        yield* Effect.log(`[LAYER 3]   Cause: ${dbError.cause.message}`);

        // Recovery decision
        return "fallback-value";
      })
    )
  );

  const result1 = yield* highLevelOperation;

  yield* Effect.log(`[RESULT] Recovered with: ${result1}\n`);

  // Example 2: Error context accumulation
  console.log(`[2] Accumulating context through layers:\n`);

  interface ErrorContext {
    timestamp: Date;
    operation: string;
    userId?: string;
    requestId: string;
  }

  const errorWithContext = (context: ErrorContext) =>
    Effect.fail(
      new BusinessLogicError({
        operation: context.operation,
        context: {
          userId: context.userId,
          timestamp: context.timestamp.toISOString(),
          requestId: context.requestId,
        },
        originalError: new Error("Operation failed"),
      })
    );

  const myContext: ErrorContext = {
    timestamp: new Date(),
    operation: "process-payment",
    userId: "user-123",
    requestId: "req-abc-def",
  };

  const withContextRecovery = errorWithContext(myContext).pipe(
    Effect.mapError((error) => {
      // Log complete context
      return {
        ...error,
        enriched: true,
        additionalInfo: {
          serviceName: "payment-service",
          environment: "production",
          version: "1.2.3",
        },
      };
    }),
    Effect.catchAll((error) =>
      Effect.gen(function* () {
        yield* Effect.log(`[ERROR CAUGHT] ${error.operation}`);
        yield* Effect.log(`[CONTEXT] ${JSON.stringify(error.context, null, 2)}`);
        return "recovered";
      })
    )
  );

  yield* withContextRecovery;

  // Example 3: Network error with retry context
  console.log(`\n[3] Network errors with retry context:\n`);

  interface RetryContext {
    attempt: number;
    maxAttempts: number;
    delay: number;
  }

  let attemptCount = 0;

  const networkCall = Effect.gen(function* () {
    attemptCount++;

    yield* Effect.log(`[ATTEMPT] ${attemptCount}/3`);

    if (attemptCount < 3) {
      yield* Effect.fail(
        new NetworkError({
          endpoint: "https://api.example.com/data",
          method: "GET",
          statusCode: 503,
          cause: new Error("Service Unavailable"),
        })
      );
    }

    return "success";
  });

  const withRetryContext = Effect.gen(function* () {
    let lastError: NetworkError | null = null;

    for (let i = 1; i <= 3; i++) {
      const result = yield* networkCall.pipe(
        Effect.catchTag("NetworkError", (error) => {
          lastError = error;

          yield* Effect.log(
            `[RETRY] Attempt ${i} failed: ${error.statusCode}`
          );

          if (i < 3) {
            yield* Effect.log(`[RETRY] Waiting before retry...`);
          }

          return Effect.fail(error);
        })
      ).pipe(
        Effect.tap(() => Effect.log(`[SUCCESS] Connected on attempt ${i}`))
      ).pipe(
        Effect.catchAll(() => Effect.succeed(null))
      );

      if (result !== null) {
        return result;
      }
    }

    if (lastError) {
      yield* Effect.fail(lastError);
    }

    return null;
  });

  const networkResult = yield* withRetryContext.pipe(
    Effect.catchAll((error) =>
      Effect.gen(function* () {
        yield* Effect.log(`[EXHAUSTED] All retries failed`);
        return "fallback";
      })
    )
  );

  yield* Effect.log(`\n`);

  // Example 4: Multi-layer error transformation
  console.log(`[4] Error transformation between layers:\n`);

  const layer1Error = Effect.gen(function* () {
    yield* Effect.fail(new Error("Raw system error"));
  });

  // Layer 2: Convert to domain error
  const layer2 = layer1Error.pipe(
    Effect.mapError((error) =>
      new DatabaseError({
        query: "SELECT ...",
        parameters: [],
        cause: error instanceof Error ? error : new Error(String(error)),
      })
    )
  );

  // Layer 3: Convert to business error
  const layer3 = layer2.pipe(
    Effect.mapError((dbError) =>
      new BusinessLogicError({
        operation: "fetch-user-profile",
        context: {
          dbError: dbError.query,
        },
        originalError: dbError.cause,
      })
    )
  );

  // Layer 4: Return user-friendly error
  const userFacingError = layer3.pipe(
    Effect.mapError((bizError) => ({
      message: "Unable to load profile",
      code: "PROFILE_LOAD_FAILED",
      originalError: bizError.originalError.message,
    })),
    Effect.catchAll((userError) =>
      Effect.gen(function* () {
        yield* Effect.log(`[USER MESSAGE] ${userError.message}`);
        yield* Effect.log(`[CODE] ${userError.code}`);
        yield* Effect.log(`[DEBUG] ${userError.originalError}`);
        return null;
      })
    )
  );

  yield* userFacingError;

  // Example 5: Error aggregation in concurrent operations
  console.log(`\n[5] Error propagation in concurrent operations:\n`);

  const operation = (id: number, shouldFail: boolean) =>
    Effect.gen(function* () {
      if (shouldFail) {
        yield* Effect.fail(
          new Error(`Operation ${id} failed`)
        );
      }

      return `result-${id}`;
    });

  const concurrent = Effect.gen(function* () {
    const results = yield* Effect.all(
      [
        operation(1, false),
        operation(2, true),
        operation(3, false),
      ],
      { concurrency: 3 }
    ).pipe(
      Effect.catchAll((errors) =>
        Effect.gen(function* () {
          yield* Effect.log(`[CONCURRENT] Caught aggregated errors`);

          // In real code, Cause provides error details
          yield* Effect.log(`[ERROR] Errors encountered during concurrent execution`);

          return [];
        })
      )
    );

    return results;
  });

  yield* concurrent;

  yield* Effect.log(`\n[DEMO] Error propagation complete`);
});

Effect.runPromise(program);

Read the full file on GitHub · 351 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 4d ago First seen · 351 lines · 2,091 tokens per session scan A bcd7bbb5ca24

Subscribe to this mod's changes

error-handling-pattern-2-error-propagation-and-chains is a cursor rule published in the GitHub repository PaulJPhilp/EffectPatterns (796 stars, last pushed 2mo ago), licensed MIT. It adds 2,091 tokens to every session, about $0.0105 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.