handling-errors

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Handling Errors

错误处理

When to use this skill

本技能的适用场景

  • Implementing error handling in new features.
  • Designing error-resilient APIs and distributed systems.
  • Improving application reliability through Circuit Breakers or Graceful Degradation.
  • Standardizing error messages and custom exception hierarchies.
  • 在新功能中实现错误处理。
  • 设计具备错误弹性的API与分布式系统。
  • 通过Circuit Breaker或Graceful Degradation提升应用可靠性。
  • 统一错误消息格式与自定义异常层级。

Workflow

工作流程

  1. Categorization
    • Determine if the error is Recoverable (e.g., Network Timeout) or Unrecoverable (e.g., OOM).
  2. Strategy Selection
    • Choose a pattern: Fail Fast, Retry, Circuit Breaker, or Graceful Degradation.
  3. Implementation
    • Use language-specific best practices (Custom Exceptions, Result Types, or Explicit Returns).
  4. Verification
    • Validate that errors are logged with context and resources are cleaned up.
  1. 错误分类
    • 判断错误属于可恢复型(如:网络超时)还是不可恢复型(如:内存不足OOM)。
  2. 策略选择
    • 选择合适的模式:快速失败(Fail Fast)重试(Retry)Circuit BreakerGraceful Degradation
  3. 落地实现
    • 遵循语言特定的最佳实践(自定义异常、结果类型或显式返回)。
  4. 验证环节
    • 验证错误是否附带上下文信息记录,且资源已被清理。

Universal Patterns

通用模式

Circuit Breaker

Circuit Breaker

Prevent cascading failures by rejecting requests when a service is failing.
python
undefined
当服务故障时,拒绝请求以防止级联失败。
python
undefined

Logic: CLOSED -> failure threshold reached -> OPEN (wait timeout) -> HALF_OPEN (test)

Logic: CLOSED -> failure threshold reached -> OPEN (wait timeout) -> HALF_OPEN (test)

undefined
undefined

Error Aggregation

错误聚合

Collect multiple errors (e.g., during validation) instead of failing on the first one.
typescript
class ErrorCollector {
  private errors: Error[] = [];
  add(error: Error) { this.errors.push(error); }
  throw() { if (this.errors.length) throw new AggregateError(this.errors); }
}
收集多个错误(如验证阶段),而非遇到第一个错误就终止。
typescript
class ErrorCollector {
  private errors: Error[] = [];
  add(error: Error) { this.errors.push(error); }
  throw() { if (this.errors.length) throw new AggregateError(this.errors); }
}

Graceful Degradation

Graceful Degradation

Provide fallback functionality (e.g., fetch from cache if DB is down).
python
def with_fallback(primary, fallback):
    try: return primary()
    except Exception: return fallback()
提供降级备选功能(如:数据库宕机时从缓存获取数据)。
python
def with_fallback(primary, fallback):
    try: return primary()
    except Exception: return fallback()

Language-Specific Patterns

语言特定模式

Python

Python

  • Hierarchy: Use
    ApplicationError(Exception)
    as a base.
  • Cleanup: Use
    @contextmanager
    or
    try/finally
    .
  • Retry: Implement decorators with exponential backoff.
  • 异常层级:
    ApplicationError(Exception)
    作为基类。
  • 资源清理: 使用
    @contextmanager
    try/finally
  • 重试机制: 实现带指数退避的装饰器。

TypeScript/JS

TypeScript/JS

  • Results: Use
    type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }
    .
  • Async: Handle Promise rejections explicitly; avoid swallowing errors in
    catch
    .
  • 结果类型: 使用
    type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }
  • 异步处理: 显式处理Promise拒绝;避免在
    catch
    中吞掉错误。

Rust/Go

Rust/Go

  • Rust: Prefer
    Result<T, E>
    and the
    ?
    operator.
  • Go: Check
    if err != nil
    explicitly; use
    fmt.Errorf("...: %w", err)
    for wrapping.
  • Rust: 优先使用
    Result<T, E>
    ?
    运算符。
  • Go: 显式检查
    if err != nil
    ;使用
    fmt.Errorf("...: %w", err)
    包装错误。

Best Practices

最佳实践

  • Fail Fast: Validate early.
  • Preserve Context: Log metadata, stack traces, and timestamps.
  • Don't Swallow Errors: Log or re-throw; empty catch blocks are forbidden.
  • Cleanup: Always close files and connections.
  • 快速失败(Fail Fast): 尽早进行验证。
  • 保留上下文: 记录元数据、堆栈跟踪与时间戳。
  • 禁止吞掉错误: 记录或重新抛出;禁止空
    catch
    块。
  • 资源清理: 始终关闭文件与连接。

Resources

参考资源

  • retry-patterns.md
  • custom-errors.ts
  • retry-patterns.md
  • custom-errors.ts