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.
git clone --depth 1 https://github.com/PaulJPhilp/EffectPatternsWrote 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.
[](https://agentmods.dev/rules/pauljphilp/effectpatterns/handle-api-errors)<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>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.
| Model | Per session | Once 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 |
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.
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
)
);
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.
- 3d ago First seen · 250 lines · 1,840 tokens per session scan A 9de4c93c298f
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.
Other cursor rules, from other repositories
fastapi-middleware
Specifies the use of middleware for logging, error monitoring, and performance optimization in FastAPI applications.
service-class-conventions
Defines the structure and implementation of service classes, enforcing the use of interfaces, ServiceImpl classes, DTOs for data transfer, and transactional management.
htmx-go-and-fiber-best-practices-general
Applies general best practices for HTMX, Go, and Fiber development to Go files. Focuses on Fiber framework usage.
fastapi-startup-and-shutdown-events
Recommends minimizing the use of startup and shutdown events in favor of lifespan context managers.
dragonruby-error-handling
Defines error handling and validation strategies within Ruby code in DragonRuby projects.
django-middleware-for-request-response
Recommends utilizing Django's middleware for handling request and response processing. Middleware allows for global actions to be performed on requests and responses.