AgentSkillsCN

handling-errors

在错误处理中防止无声失败与上下文丢失。当您需要编写 try-catch 块、设计错误传播机制、审查 catch 块,或实施 Result 模式时,可使用此技能。

SKILL.md
--- frontmatter
name: handling-errors
description: Prevents silent failures and context loss in error handling. Use when writing try-catch blocks, designing error propagation, reviewing catch blocks, or implementing Result patterns.

Handling Errors

Iron Laws

  1. Never swallow errors - Empty catch blocks hide bugs
  2. Never convert errors to booleans - Loses all context
  3. Preserve error context when wrapping or propagating
  4. Log once where handled, not at every layer

Error Messages

Every error message answers: What happened? Why? How to recover?

For logs (developers):

typescript
logger.error("Failed to save user: Connection timeout after 30s", {
  userId: user.id,
  dbHost: config.db.host,
  error: error.stack,
});

For users:

For user-facing error copy, use Skill(ce:writer) with The UX Writer persona. Key principles:

  • Brief and specific (not "Something went wrong")
  • Actionable (tell them what to do next)
  • No blame (never "You entered invalid...")
typescript
showError({
  title: "Upload failed",
  message: "File exceeds 10MB limit. Choose a smaller file.",
  actions: [{ label: "Choose file", onClick: selectFile }],
});

Error Categories

TypeExamplesHandling
ExpectedValidation, Not found, UnauthorizedReturn Result type, log info
TransientNetwork timeout, Rate limitRetry with backoff, log warn
UnexpectedNull reference, DB crashLog error, show support ID
CriticalAuth down, Payment gateway offlineCircuit breaker, alert

Fail Fast vs Degrade Gracefully

Fail fast for critical dependencies:

typescript
await connectToDatabase(); // Throws on failure - app can't run without it

Degrade gracefully for optional features:

typescript
const prefs = await loadPreferences(userId).catch(() => DEFAULT_PREFS);

Log at the Right Layer

typescript
// ❌ Logging at every layer = same error 3x
async function fetchData() {
  try { return await fetch(url); }
  catch (e) { console.error("Fetch failed:", e); throw e; }
}

// ✅ Log once where handled
async function fetchData() {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response;
}
// Top level logs the error once

Language-Specific Patterns

Anti-Patterns

PatternProblemFix
Empty catch blocksHides errorsLog or re-throw
return false on errorLoses contextReturn Result type
Generic "Error" messagesUndebuggableInclude what/why/context
Logging same error at each layerLog pollutionLog once at boundary
Bare except: / catch (e) allCatches system signalsCatch specific types