handle-api-errors

handle-api-errors is a cursor rule for Cursor from PaulJPhilp/EffectPatterns. It costs 1,840 tokens per session, scanned A, original, MIT.

An API error-handling pattern that represents application errors as named types and converts them into specific HTTP responses.

In plain words
What is it for?
Use it to map errors from API routes to responses such as 400, 404, and 500.
Why use it?
It prevents every failure from becoming an unclear server error and lets clients distinguish cases such as missing data, invalid input, and unexpected failures.

Cursor rule for Cursor

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

Good fit Use it to map errors from API routes to responses such as…

Compare 6 cursor rules from other repositories ↓
Install with agentmods
npx agentmods add rules/pauljphilp/effectpatterns/handle-api-errors
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 handle-api-errors

README.md
[![agentmods](https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/handle-api-errors.svg)](https://agentmods.dev/rules/pauljphilp/effectpatterns/handle-api-errors)
Your own site
<a href="https://agentmods.dev/rules/pauljphilp/effectpatterns/handle-api-errors"><img src="https://agentmods.dev/badge/rules/pauljphilp/effectpatterns/handle-api-errors.svg" alt="Measured on agentmods" height="20"></a>
Per session 1,840 This file is loaded in full into every session.
When invoked 1,840 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.01840 $0.01840
Opus 5 $0.00920 $0.00920
Sonnet 5 $0.00368 $0.00368
Haiku 4.5 $0.00184 $0.00184

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

Security

Grade A, and why

handle-api-errors 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 3d 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/handle-api-errors.mdc · 250 lines

How it starts

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

description: Model application errors as typed classes and use Http.server.serveOptions to map them to specific HTTP responses. globs: "**/*.ts" alwaysApply: true

Handle API Errors

Rule: Model application errors as typed classes and use Http.server.serveOptions to map them to specific HTTP responses.

Example

This example defines two custom error types, UserNotFoundError and InvalidIdError. The route logic can fail with either. The unhandledErrorResponse function inspects the error and returns a 404 or 400 response accordingly, with a generic 500 for any other unexpected errors.

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

// Define our domain types
export interface User {
  readonly id: string;
  readonly name: string;
  readonly email: string;
  readonly role: "admin" | "user";
}

// Define specific, typed errors for our domain
export class UserNotFoundError extends Data.TaggedError("UserNotFoundError")<{
  readonly id: string;
}> {}

export class InvalidIdError extends Data.TaggedError("InvalidIdError")<{
  readonly id: string;
  readonly reason: string;
}> {}

export class UnauthorizedError extends Data.TaggedError("UnauthorizedError")<{
  readonly action: string;
  readonly role: string;
}> {}

// Define error handler service
export class ErrorHandlerService extends Effect.Service<ErrorHandlerService>()(
  "ErrorHandlerService",
  {
    sync: () => ({
      // Handle API errors with proper logging
      handleApiError: <E>(error: E): Effect.Effect<ApiResponse, never, never> =>
        Effect.gen(function* () {
          yield* Effect.logError(`API Error: ${JSON.stringify(error)}`);

          if (error instanceof UserNotFoundError) {
            return {
              error: "Not Found",
              message: `User ${error.id} not found`,
            };
          }
          if (error instanceof InvalidIdError) {
            return { error: "Bad Request", message: error.reason };
          }
          if (error instanceof UnauthorizedError) {
            return {
              error: "Unauthorized",
              message: `${error.role} cannot ${error.action}`,
            };
          }

          return {
            error: "Internal Server Error",
            message: "An unexpected error occurred",
          };
        }),

      // Handle unexpected errors
      handleUnexpectedError: (
        cause: Cause.Cause<unknown>
      ): Effect.Effect<void, never, never> =>
        Effect.gen(function* () {
          yield* Effect.logError("Unexpected error occurred");

          if (Cause.isDie(cause)) {
            const defect = Cause.failureOption(cause);
            if (defect._tag === "Some") {
              const error = defect.value as Error;
              yield* Effect.logError(`Defect: ${error.message}`);
              yield* Effect.logError(
                `Stack: ${error.stack?.split("\n")[1]?.trim() ?? "N/A"}`
              );
            }
          }

          return Effect.succeed(void 0);
        }),
    }),
  }
) {}

// Define UserRepository service
export class UserRepository extends Effect.Service<UserRepository>()(
  "UserRepository",
  {
    sync: () => {
      const users = new Map<string, User>([
        [
          "user_123",
          {
            id: "user_123",
            name: "Paul",
            email: "[email protected]",
            role: "admin",
          },
        ],
        [
          "user_456",
          {
            id: "user_456",
            name: "Alice",
            email: "[email protected]",
            role: "user",
          },
        ],
      ]);

      return {
        // Get user by ID with proper error handling
        getUser: (
          id: string
        ): Effect.Effect<User, UserNotFoundError | InvalidIdError> =>
          Effect.gen(function* () {
            yield* Effect.logInfo(`Attempting to get user with id: ${id}`);

            // Validate ID format
            if (!id.match(/^user_\d+$/)) {
              yield* Effect.logWarning(`Invalid user ID format: ${id}`);
              return yield* Effect.fail(
                new InvalidIdError({
                  id,
                  reason: "ID must be in format user_<number>",
                })
              );
            }

            const user = users.get(id);
            if (user === undefined) {
              yield* Effect.logWarning(`User not found with id: ${id}`);
              return yield* Effect.fail(new UserNotFoundError({ id }));
            }

            yield* Effect.logInfo(`Found user: ${JSON.stringify(user)}`);
            return user;
          }),

        // Check if user has required role
        checkRole: (
          user: User,
          requiredRole: "admin" | "user"
        ): Effect.Effect<void, UnauthorizedError> =>
          Effect.gen(function* () {
            yield* Effect.logInfo(
              `Checking if user ${user.id} has role: ${requiredRole}`
            );

            if (user.role !== requiredRole && user.role !== "admin") {
              yield* Effect.logWarning(
                `User ${user.id} with role ${user.role} cannot access ${requiredRole} resources`
              );
              return yield* Effect.fail(
                new UnauthorizedError({
                  action: "access_user",
                  role: user.role,
                })
              );
            }

            yield* Effect.logInfo(
              `User ${user.id} has required role: ${user.role}`
            );
            return Effect.succeed(void 0);
          }),
      };
    },
  }
) {}

interface ApiResponse {
  readonly error?: string;
  readonly message?: string;
  readonly data?: User;
}

// Create routes with proper error handling
const createRoutes = () =>
  Effect.gen(function* () {
    const repo = yield* UserRepository;
    const errorHandler = yield* ErrorHandlerService;

    yield* Effect.logInfo("=== Processing API request ===");

    // Test different scenarios
    for (const userId of ["user_123", "user_456", "invalid_id", "user_789"]) {
      yield* Effect.logInfo(`\n--- Testing user ID: ${userId} ---`);

      const response = yield* repo.getUser(userId).pipe(
        Effect.map((user) => ({
          data: {
            ...user,
            email: user.role === "admin" ? user.email : "[hidden]",
          },
        })),
        Effect.catchAll((error) => errorHandler.handleApiError(error))
      );

      yield* Effect.logInfo(`Response: ${JSON.stringify(response)}`);
    }

    // Test role checking
    const adminUser = yield* repo.getUser("user_123");
    const regularUser = yield* repo.getUser("user_456");

    yield* Effect.logInfo("\n=== Testing role checks ===");

    yield* repo.checkRole(adminUser, "admin").pipe(
      Effect.tap(() => Effect.logInfo("Admin access successful")),
      Effect.catchAll((error) => errorHandler.handleApiError(error))
    );

    yield* repo.checkRole(regularUser, "admin").pipe(
      Effect.tap(() => Effect.logInfo("User admin access successful")),
      Effect.catchAll((error) => errorHandler.handleApiError(error))
    );

    return { message: "Tests completed successfully" };
  });

// Run the program with all services
Effect.runPromise(
  Effect.provide(
    Effect.provide(createRoutes(), ErrorHandlerService.Default),
    UserRepository.Default
  )
);

Read the full file on GitHub · 250 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. 3d ago First seen · 250 lines · 1,840 tokens per session scan A 9de4c93c298f

Subscribe to this mod's changes

handle-api-errors is a cursor rule published in the GitHub repository PaulJPhilp/EffectPatterns (796 stars, last pushed 2mo ago), licensed MIT. It adds 1,840 tokens to every session, about $0.0092 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.