Agent SkillsDanielPodolsky/ownyourcode › error-handling-fundamentals

error-handling-fundamentals

GitHub

指导异步操作和API调用的错误处理最佳实践。涵盖try/catch、Promise链及网络请求,提供检查清单与反模式示例,确保错误捕获有意义、用户提示友好且日志记录完善。

.claude/skills/fundamentals/error-handling/SKILL.md DanielPodolsky/ownyourcode

Trigger Scenarios

询问如果失败怎么办 处理错误 使用 try catch 网络错误 构建涉及 fetch、promises 或外部服务的功能

Install

npx skills add DanielPodolsky/ownyourcode --skill error-handling-fundamentals -g -y
More Options

Non-standard path

npx skills add https://github.com/DanielPodolsky/ownyourcode/tree/main/.claude/skills/fundamentals/error-handling -g -y

Use without installing

npx skills use DanielPodolsky/ownyourcode@error-handling-fundamentals

指定 Agent (Claude Code)

npx skills add DanielPodolsky/ownyourcode --skill error-handling-fundamentals -a claude-code -g -y

安装 repo 全部 skill

npx skills add DanielPodolsky/ownyourcode --all -g -y

预览 repo 内 skill

npx skills add DanielPodolsky/ownyourcode --list

SKILL.md

Frontmatter
{
    "name": "error-handling-fundamentals",
    "description": "Guides error handling for async operations and API calls. Use when junior asks \"what if this fails\", \"handle errors\", \"try catch\", \"network error\", or builds features with fetch, promises, or external services."
}

Error Handling Fundamentals Review

"Errors are not failures — they're information. Handle them like the valuable data they are."

When to Apply

Activate this skill when reviewing:

  • try/catch blocks
  • Promise chains (.then/.catch)
  • API error responses
  • Form validation
  • Network request handling
  • User-facing error messages

Review Checklist

Error Catching

  • No empty catches: Is every catch block doing something meaningful?
  • Proper scope: Are errors caught at the right level?
  • Context added: Do errors include helpful debugging info?
  • Finally used: Are cleanup operations in finally blocks?

User Experience

  • User-friendly messages: Will users understand the error?
  • No technical details exposed: Are stack traces hidden from users?
  • Actionable feedback: Does the error tell users what to do next?
  • Graceful degradation: Does the app still work partially on error?

Logging & Debugging

  • Errors logged: Are errors recorded for debugging?
  • Context in logs: Do logs include request ID, user ID, etc.?
  • Severity levels: Are critical errors distinguished from warnings?

Recovery

  • Retry logic: Should this operation retry on failure?
  • Fallback values: Is there a sensible default on error?
  • Loading states: Is the user informed while retrying?

Common Mistakes (Anti-Patterns)

1. The Empty Catch (The Silent Killer)

❌ try {
     await submitForm();
   } catch (error) {
     // TODO: handle later (never happens)
   }

✅ try {
     await submitForm();
   } catch (error) {
     console.error('Form submission failed:', error);
     setError('Could not submit. Please try again.');
   }

2. Catching Too Early

❌ function getUser(id) {
     try {
       return database.query(id);
     } catch {
       return null; // Caller has no idea it failed
     }
   }

✅ function getUser(id) {
     return database.query(id); // Let caller decide
   }

   // In UI layer
   try {
     const user = await getUser(id);
   } catch (error) {
     showToast('Could not load user');
   }

3. Generic Error Messages

❌ catch (error) {
     setError('An error occurred');
   }

✅ catch (error) {
     if (error.code === 'NETWORK_ERROR') {
       setError('Check your internet connection');
     } else if (error.code === 'NOT_FOUND') {
       setError('User not found');
     } else {
       setError('Something went wrong. Please try again.');
     }
   }

4. Leaking Stack Traces

❌ res.status(500).json({
     error: error.message,
     stack: error.stack
   });

✅ logger.error('Request failed', { error, requestId });
   res.status(500).json({
     error: 'Something went wrong'
   });

5. Forgetting Finally

❌ try {
     setLoading(true);
     await fetchData();
     setLoading(false);
   } catch (error) {
     handleError(error);
     // Loading stays true forever!
   }

✅ try {
     setLoading(true);
     await fetchData();
   } catch (error) {
     handleError(error);
   } finally {
     setLoading(false); // Always runs
   }

Socratic Questions

Ask the junior these questions instead of giving answers:

  1. Empty Catch: "What happens if this fails silently?"
  2. User Message: "If you were the user, would this message help you?"
  3. Recovery: "Should we retry this automatically?"
  4. Scope: "Is this the right place to catch this error?"
  5. Logging: "How will you debug this in production?"

Error Message Guidelines

Do

  • Be specific: "The email address is already registered"
  • Be helpful: "Please check your internet connection"
  • Offer next steps: "Try again" or "Contact support"
  • Match severity: Critical errors need more attention than warnings

Don't

  • Show technical details: TypeError: Cannot read property 'map' of undefined
  • Be vague: "An error occurred"
  • Blame the user: "You entered invalid data"
  • Use jargon: "HTTP 500 Internal Server Error"

Error Handling Patterns

API/Network Errors

async function fetchWithRetry(url: string, retries = 3): Promise<Response> {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return response;
  } catch (error) {
    if (retries > 0) {
      await sleep(1000);
      return fetchWithRetry(url, retries - 1);
    }
    throw error;
  }
}

Form Validation

function validateForm(data: FormData) {
  const errors: Record<string, string> = {};

  if (!data.email) {
    errors.email = 'Email is required';
  } else if (!isValidEmail(data.email)) {
    errors.email = 'Please enter a valid email';
  }

  return {
    isValid: Object.keys(errors).length === 0,
    errors
  };
}

React Error Boundaries

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    logError(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <FallbackUI />;
    }
    return this.props.children;
  }
}

Standards Reference

See detailed patterns in:

  • /standards/global/error-handling.md

Red Flags to Call Out

Flag Question to Ask
Empty catch block "What happens when this fails?"
catch (e) { return null } "How will the caller know it failed?"
No loading state "What does the user see while waiting?"
Technical error shown "Will the user understand this message?"
No finally for cleanup "Is loading state stuck on error?"
console.log instead of error "How will you find this in production logs?"

Version History

  • bd1f17c Current 2026-07-11 17:35

Same Skill Collection

.claude/skills/career/resume-bullets/SKILL.md
.claude/skills/career/star-stories/SKILL.md
.claude/skills/fundamentals/accessibility/SKILL.md
.claude/skills/fundamentals/backend/SKILL.md
.claude/skills/fundamentals/database/SKILL.md
.claude/skills/fundamentals/debugging/SKILL.md
.claude/skills/fundamentals/documentation/SKILL.md
.claude/skills/fundamentals/engineering/SKILL.md
.claude/skills/fundamentals/frontend/SKILL.md
.claude/skills/fundamentals/performance/SKILL.md
.claude/skills/fundamentals/resistance/SKILL.md
.claude/skills/fundamentals/security/SKILL.md
.claude/skills/fundamentals/seo/SKILL.md
.claude/skills/fundamentals/testing/SKILL.md
.claude/skills/gates/error/SKILL.md
.claude/skills/gates/fundamentals/SKILL.md
.claude/skills/gates/ownership/SKILL.md
.claude/skills/gates/performance/SKILL.md
.claude/skills/gates/security/SKILL.md
.claude/skills/gates/testing/SKILL.md

Metadata

Files
0
Version
bd1f17c
Hash
e9b75b35
Indexed
2026-07-11 17:35

Home - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-14 09:26
浙ICP备14020137号-1 $Map of visitor$