技能 error-handling-patterns
📦

error-handling-patterns

安全

Implementar Padrões Robustos de Tratamento de Erros

也可从以下获取: wshobson

Construa aplicações mais resilientes dominando padrões de tratamento de erros incluindo exceções, tipos Result, lógica de retry e circuit breakers em Python, TypeScript, Rust e Go.

支持: Claude Codex Code(CC)
🥉 75 青铜
1

下载技能 ZIP

2

在 Claude 中上传

前往 设置 → 功能 → 技能 → 上传技能

3

开启并开始使用

测试它

正在使用“error-handling-patterns”。 How do I handle errors when calling an external API?

预期结果:

For external API calls, implement multiple layers of error handling: (1) Custom exception hierarchy for different failure types, (2) Retry with exponential backoff for transient errors, (3) Circuit breaker to prevent cascading failures, (4) Graceful degradation with fallback data. Example approach: Create custom exceptions (NetworkError, TimeoutError, RateLimitError), wrap API calls in retry decorator with 3 attempts and exponential backoff, use circuit breaker to track failure rates, provide cached fallback when API is unavailable.

正在使用“error-handling-patterns”。 When should I use Result types instead of exceptions?

预期结果:

Use Result types for expected failures (validation errors, not found errors, business logic errors) where the caller should explicitly handle both success and failure cases. Use exceptions for truly exceptional situations (null pointers, out of memory, unexpected runtime errors). Result types make error handling explicit in the type system, forcing callers to consider failure cases. In TypeScript, Result<T, E> = { ok: true, value: T } | { ok: false, error: E }. In Rust, the ? operator and Result<T, E> type provide built-in support. This approach improves code readability and reduces unexpected runtime errors.

安全审计

安全
v1 • 2/24/2026

This skill is a documentation and educational resource about error handling patterns. The static scanner flagged 49 potential issues, but after evaluation all findings are FALSE POSITIVES. The detected patterns (backtick syntax examples, HTTP library examples, error categories) are educational code snippets in markdown documentation, not executable malicious code. No security concerns identified.

2
已扫描文件
674
分析行数
0
发现项
1
审计总数
未发现安全问题
审计者: claude

质量评分

38
架构
100
可维护性
87
内容
50
社区
100
安全
100
规范符合性

你能构建什么

Melhorar Confiabilidade de Aplicações

Adicione tratamento de erros robusto a recursos novos ou existentes com hierarquias de exceções apropriadas e mensagens de erro significativas.

Construir Sistemas Tolerantes a Falhas

Implemente lógica de retry, circuit breakers e degradação graceful para sistemas distribuídos e microsserviços.

Aprender Padrões Multi-linguagem

Entenda abordagens de tratamento de erros em Python, TypeScript, Rust e Go para escolher a melhor abordagem para cada situação.

试试这些提示

Tratamento Básico de Exceções
Help me implement proper error handling for a function that fetches user data from a database. I want to create custom exception classes and handle different error scenarios appropriately.
Implementação de Result Type
Show me how to implement a Result type pattern in TypeScript for parsing JSON data. Include proper error types and chainable error handling.
Retry com Backoff
Create a Python decorator that implements retry logic with exponential backoff for network calls. Handle different exception types and include configurable attempts.
Padrão Circuit Breaker
Implement a circuit breaker pattern in Python to prevent cascading failures when calling an external API. Include closed, open, and half-open states.

最佳实践

  • Fail fast by validating input early and providing meaningful error messages with context
  • Preserve error context including stack traces, timestamps, and relevant metadata
  • Handle errors at the appropriate level where you can meaningfully respond to them
  • Log errors appropriately - log unexpected errors, not expected validation failures

避免

  • Catching too broadly with generic Exception handlers that hide bugs
  • Empty catch blocks that silently swallow errors without logging or handling
  • Returning error codes instead of using proper exceptions or Result types
  • Ignoring async errors by not handling promise rejections properly

常见问题

What is the difference between exceptions and Result types?
Exceptions are traditional error handling that disrupts control flow with try-catch blocks. Result types are explicit success/failure types that require the caller to handle both cases. Result types make error handling visible in the type system and are common in functional programming languages like Rust and Haskell.
When should I use a circuit breaker?
Use a circuit breaker when calling external services or APIs that might become unavailable. It prevents cascading failures by failing fast when a service is down, rather than tying up resources with repeated failing requests. The circuit transitions between closed (normal), open (failing), and half-open (testing recovery) states.
How does exponential backoff work for retries?
Exponential backoff increases the wait time between retry attempts (e.g., 1 second, 2 seconds, 4 seconds, 8 seconds). This prevents overwhelming a failing service with repeated requests while still giving it time to recover. Add jitter (random variation) to prevent thundering herd problems.
What is graceful degradation?
Graceful degradation provides fallback functionality when an error occurs. For example, if a caching service fails, fall back to the database. If both fail, return cached stale data. The application continues to work with reduced functionality rather than failing completely.
Should I catch exceptions or let them propagate?
Catch exceptions only where you can meaningfully handle them. Let unexpected exceptions propagate to a centralized error handler that logs them appropriately. This prevents hiding bugs with overly broad catch blocks while ensuring errors are properly logged and reported.
How do I create meaningful error messages?
Good error messages include what failed, why it failed, and what action to take. Include relevant context like user IDs, request IDs, and timestamps. Avoid generic messages like 'Error occurred' - instead say 'Failed to fetch user profile for user ID 123: connection timeout after 30s'.