error-handling-patterns
Standard patterns for error handling, retry logic, circuit breakers, and graceful degradation.
التثبيت باستخدام Codex أو Claude انسخ هذا Prompt والصقه في Codex أو Claude أو مساعد آخر ليراجع صفحة Skill ويثبّتها لك.
القائمة
Standard patterns for error handling, retry logic, circuit breakers, and graceful degradation.
التثبيت باستخدام Codex أو Claude انسخ هذا Prompt والصقه في Codex أو Claude أو مساعد آخر ليراجع صفحة Skill ويثبّتها لك.
استنادا إلى تصنيف SOC المهني
| name | error-handling-patterns |
| description | Standard patterns for error handling, retry logic, circuit breakers, and graceful degradation. |
Provide reusable error handling patterns to make applications resilient and debuggable.
Define error types by category, not by source:
class AppError extends Error {
constructor(
message: string,
public readonly code: string, // machine-readable: "AUTH_EXPIRED"
public readonly statusCode: number, // HTTP-compatible: 401
public readonly isOperational: boolean = true // true = expected, false = bug
) {
super(message);
this.name = "AppError";
}
}
// Usage
throw new AppError("Token expired", "AUTH_EXPIRED", 401, true);
Rule: operational errors are handled; non-operational errors crash and alert.
async function withRetry<T>(
fn: () => Promise<T>,
options: { maxAttempts?: number; baseDelayMs?: number; maxDelayMs?: number } = {}
): Promise<T> {
const { maxAttempts = 3, baseDelayMs = 200, maxDelayMs = 5000 } = options;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxAttempts) throw error;
if (error instanceof AppError && !error.isOperational) throw error; // don't retry bugs
const delay = Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs);
const jitter = delay * (0.5 + Math.random() * 0.5);
await new Promise(r => setTimeout(r, jitter));
}
}
throw new Error("Unreachable");
}
Rules:
class CircuitBreaker {
private failures = 0;
private lastFailure = 0;
private state: "closed" | "open" | "half-open" = "closed";
constructor(
private threshold: number = 5,
private resetTimeoutMs: number = 30000
) {}
async execute<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === "open") {
if (Date.now() - this.lastFailure > this.resetTimeoutMs) {
this.state = "half-open";
} else {
throw new AppError("Service unavailable (circuit open)", "CIRCUIT_OPEN", 503);
}
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
private onSuccess() { this.failures = 0; this.state = "closed"; }
private onFailure() {
this.failures++;
this.lastFailure = Date.now();
if (this.failures >= this.threshold) this.state = "open";
}
}
Use when: calling external services that may be down for extended periods.
When a non-critical feature fails, degrade instead of crashing:
| Failure | Degradation |
|---|---|
| Recommendation engine down | Show popular items instead |
| Analytics service unreachable | Queue events for later, continue serving |
| CDN image unavailable | Show placeholder image |
| Cache miss | Fall through to database (slower but functional) |
Rule: only non-critical features degrade; critical paths must fail explicitly.
When a failure affects canonical queue state, do not hide it behind a friendly fallback. Instead:
blocked or needs_recovery when the lifecycle truly cannot continueExample:
{
"action": "checkpoint",
"sessionToken": "ST-...",
"input": {
"title": "Dependency API unavailable",
"summary": "Customer-safe response drafted, but the upstream API stayed unavailable after bounded retries.",
"taskStatus": "blocked",
"nextStep": "Retry after platform approval or switch to the documented manual fallback.",
"persistToMem0": false
}
}
This keeps the failure visible to next_action, audit/export surfaces, and later recovery work instead of pretending the task succeeded.
systematic-debugging — when errors need root-cause investigationtesting-policy — test error paths, not just happy pathssession-lifecycle — checkpoint or close blocked/recovery states explicitlycatch (e) { /* ignore */ }console.error(e) without state/input dataRules and strategies for managing agent context window size, avoiding bloat, and preserving signal-to-noise ratio.
Detect and remove contradictions across agent policies before execution.
Multi-step tool workflows via code orchestration to reduce latency, context pollution, and token overhead.
Bind project-specific prompts to local schema and workflow artifacts while keeping the harness core generic and globally reusable.
Operational session protocol for task-scoped leases, reconciliation, checkpoints, inspection, queue promotion, and handoff across long-running work.
Operational session protocol for task-scoped leases, reconciliation, checkpoints, inspection, queue promotion, and handoff across long-running work.