handling-errors
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHandling 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
工作流程
- Categorization
- Determine if the error is Recoverable (e.g., Network Timeout) or Unrecoverable (e.g., OOM).
- Strategy Selection
- Choose a pattern: Fail Fast, Retry, Circuit Breaker, or Graceful Degradation.
- Implementation
- Use language-specific best practices (Custom Exceptions, Result Types, or Explicit Returns).
- Verification
- Validate that errors are logged with context and resources are cleaned up.
- 错误分类
- 判断错误属于可恢复型(如:网络超时)还是不可恢复型(如:内存不足OOM)。
- 策略选择
- 选择合适的模式:快速失败(Fail Fast)、重试(Retry)、Circuit Breaker或Graceful Degradation。
- 落地实现
- 遵循语言特定的最佳实践(自定义异常、结果类型或显式返回)。
- 验证环节
- 验证错误是否附带上下文信息记录,且资源已被清理。
Universal Patterns
通用模式
Circuit Breaker
Circuit Breaker
Prevent cascading failures by rejecting requests when a service is failing.
python
undefined当服务故障时,拒绝请求以防止级联失败。
python
undefinedLogic: CLOSED -> failure threshold reached -> OPEN (wait timeout) -> HALF_OPEN (test)
Logic: CLOSED -> failure threshold reached -> OPEN (wait timeout) -> HALF_OPEN (test)
undefinedundefinedError 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 as a base.
ApplicationError(Exception) - Cleanup: Use or
@contextmanager.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 and the
Result<T, E>operator.? - Go: Check explicitly; use
if err != nilfor wrapping.fmt.Errorf("...: %w", err)
- 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