微算力 · API 导航与自营网关
API 接入 EN
未登录登录
🛡️

构建高韧性系统的错误处理指南

API Error Handling · v1.0.0
开发 安全 S 级 作者 wpank 公开目录收录
2k 下载 0 安装 8.1k 收藏 23 浏览

简介

系统性错误处理设计指南,覆盖多语言模式、熔断降级、HTTP响应规范及可观测性实践,帮助构建高韧性服务架构

原始描述

Error handling patterns across languages and layers — operational vs programmer errors, retry strategies, circuit breakers, error boundaries, HTTP responses, graceful degradation, and structured logging. Use when designing error strategies, building resilient APIs, or reviewing error management.

通过你的 Agent 添加

安装目录:error-handling/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。

点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。

或者手动安装

Claude Code~/.claude/skills/api-error-handling-24511/
Codex CLI~/.codex/skills/api-error-handling-24511/
DeepSeek Harness~/.agents/skills/api-error-handling-24511/

包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可; 目录名不用换,也不要把包直接解压到 skills 根目录。 技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。

中文使用说明 来自收录源

核心用法

本 Skill 是一套面向全栈开发者的错误处理设计模式库,聚焦三大核心场景:API 边界错误治理、跨服务容错机制、可观测性体系建设。内容采用「原则 → 分类 → 实现 → 反模式」的递进结构,提供可直接落地的代码范式。

关键能力矩阵:

  • 错误分类治理:区分 Operational(网络超时、输入非法)与 Programmer(空指针、类型错误)两类错误,前者优雅降级,后者快速崩溃
  • 语言特定模式:JavaScript(Error 子类化)、Go(error wrapping)、Rust(Result 类型)等 4 种语言的 idiomatic 实践
  • 弹性基础设施:指数退避 + 抖动重试、熔断器(Circuit Breaker)、舱壁隔离(Bulkhead)的完整实现
  • HTTP 语义化:401/403/422/429 等状态码的精确使用场景,配套标准错误信封(error envelope)格式
  • 可观测性:结构化日志、追踪 ID 透传、错误聚合监控的集成方案

显著优点

  1. 生产级完备性:熔断器、退避算法等复杂模式提供可直接复制的类/函数实现,非仅概念描述
  2. 多语言覆盖:同一设计原则在 JS/Go/Python/Rust 中的差异化实现,降低团队技术栈迁移成本
  3. 反模式清单:8 条「NEVER Do」红线和 8 类 Anti-Patterns 对照表,规避常见工程陷阱
  4. 分层边界思维:强调「在边界处处理错误」(Controller/Gateway),避免各层重复捕获导致的上下文丢失

潜在局限

  • 框架耦合示例:Express/Error Boundary 等示例偏向 Node/React 生态,Java/Spring 或 .NET 开发者需自行映射
  • 同步场景偏重:对异步流(RxJS、Kotlin Coroutines、C# async streams)的错误传播模式覆盖不足
  • 缺少压测参数:熔断器阈值(5 次失败)、退避基数(1s)等数值未说明推导依据,需结合服务 SLA 调整

适合人群

  • 设计微服务交互协议的后端架构师
  • 构建 SDK 或内部平台的基础设施工程师
  • 需统一团队错误处理规范的技术负责人
  • 排查线上诡异「静音失败」问题的SRE/运维开发者

常规风险

  1. 过度容错陷阱:盲目应用「优雅降级」可能掩盖核心业务失败,需明确「关键路径」与「增强功能」边界
  2. 重试风暴:未配抖动的指数退避在故障恢复瞬间可能引发 thundering herd,建议结合断路器状态动态调整
  3. 日志敏感信息泄露:示例中的错误信封包含 requestId,若复制到前端需确保不附带 userId 等 PII 字段

技能正文


name: error-handling model: standard description: Error handling patterns across languages and layers — operational vs programmer errors, retry strategies, circuit breakers, error boundaries, HTTP responses, graceful degradation, and structured logging. Use when designing error strategies, building resilient APIs, or reviewing error management.

Error Handling Patterns

Ship resilient software. Handle errors at boundaries, fail fast and loud, never swallow exceptions silently.

Error Handling Philosophy

Principle Description
Fail Fast Detect errors early — validate inputs at the boundary, not deep in business logic
Fail Loud Errors must be visible — log them, surface them, alert on them
Handle at Boundaries Catch and translate errors at layer boundaries (controller, middleware, gateway)
Let It Crash For unrecoverable state, crash and restart (Erlang/OTP philosophy)
Be Specific Catch specific error types, never bare catch or except
Provide Context Every error carries enough context to diagnose without reproducing

Error Types

Operational errors — network timeouts, invalid user input, file not found, DB connection lost. Handle gracefully.

Programmer errors — TypeError, null dereference, assertion failures. Fix the code — don't catch and suppress.

// Operational — handle gracefully
try {
  const data = await fetch('/api/users');
} catch (err) {
  if (err.code === 'ECONNREFUSED') return fallbackData;
  throw err; // re-throw unexpected errors
}

// Programmer — let it crash, fix the bug
const user = null;
user.name; // TypeError — don't try/catch this

Language Patterns

Language Mechanism Anti-Pattern
JavaScript try/catch, Promise.catch, Error subclasses .catch(() => {}) swallowing errors
Python Exceptions, context managers (with) Bare except: catching everything
Go error returns, errors.Is/As, fmt.Errorf wrapping _ = riskyFunction() ignoring error
Rust Result<T, E>, Option<T>, ? operator .unwrap() in production code

JavaScript — Error Subclasses

class AppError extends Error {
  constructor(message, code, statusCode, details = {}) {
    super(message);
    this.name = this.constructor.name;
    this.code = code;
    this.statusCode = statusCode;
    this.details = details;
    this.isOperational = true;
  }
}

class NotFoundError extends AppError {
  constructor(resource, id) {
    super(`${resource} not found`, 'NOT_FOUND', 404, { resource, id });
  }
}

class ValidationError extends AppError {
  constructor(errors) {
    super('Validation failed', 'VALIDATION_ERROR', 422, { errors });
  }
}

Go — Error Wrapping

func GetUser(id string) (*User, error) {
    row := db.QueryRow("SELECT * FROM users WHERE id = $1", id)
    var user User
    if err := row.Scan(&user.ID, &user.Name); err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return nil, fmt.Errorf("user %s: %w", id, ErrNotFound)
        }
        return nil, fmt.Errorf("querying user %s: %w", id, err)
    }
    return &user, nil
}

Error Boundaries

Express Error Middleware

app.use((err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  const response = {
    error: {
      code: err.code || 'INTERNAL_ERROR',
      message: err.isOperational ? err.message : 'Something went wrong',
      ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
      requestId: req.id,
    },
  };

  logger.error('Request failed', {
    err, requestId: req.id, method: req.method, path: req.path,
  });

  res.status(statusCode).json(response);
});

React Error Boundary

import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({ error, resetErrorBoundary }) {
  return (
    <div role="alert">
      <h2>Something went wrong</h2>
      <pre>{error.message}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

<ErrorBoundary FallbackComponent={ErrorFallback} onReset={() => queryClient.clear()}>
  <App />
</ErrorBoundary>

Retry Patterns

Pattern When to Use Config
Exponential Backoff Transient failures (network, 503) Base 1s, max 30s, factor 2x
Backoff + Jitter Multiple clients retrying Random ±30% on each delay
Circuit Breaker Downstream service failing repeatedly Open after 5 failures, half-open after 30s
Bulkhead Isolate failures to prevent cascade Limit concurrent calls per service
Timeout Prevent indefinite hangs Connect 5s, read 30s, total 60s

Exponential Backoff with Jitter

async function withRetry(fn, { maxRetries = 3, baseDelay = 1000, maxDelay = 30000 } = {}) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt === maxRetries || !isRetryable(err)) throw err;
      const delay = Math.min(baseDelay * 2 ** attempt, maxDelay);
      const jitter = delay * (0.7 + Math.random() * 0.6);
      await new Promise((r) => setTimeout(r, jitter));
    }
  }
}

function isRetryable(err) {
  return [408, 429, 500, 502, 503, 504].includes(err.statusCode) || err.code === 'ECONNRESET';
}

Circuit Breaker

class CircuitBreaker {
  constructor({ threshold = 5, resetTimeout = 30000 } = {}) {
    this.state = 'CLOSED';       // CLOSED → OPEN → HALF_OPEN → CLOSED
    this.failureCount = 0;
    this.threshold = threshold;
    this.resetTimeout = resetTimeout;
    this.nextAttempt = 0;
  }

  async call(fn) {
    if (this.state === 'OPEN') {
      if (Date.now() < this.nextAttempt) throw new Error('Circuit is OPEN');
      this.state = 'HALF_OPEN';
    }
    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (err) {
      this.onFailure();
      throw err;
    }
  }

  onSuccess() { this.failureCount = 0; this.state = 'CLOSED'; }
  onFailure() {
    this.failureCount++;
    if (this.failureCount >= this.threshold) {
      this.state = 'OPEN';
      this.nextAttempt = Date.now() + this.resetTimeout;
    }
  }
}

HTTP Error Responses

Status Name When to Use
400 Bad Request Malformed syntax, invalid JSON
401 Unauthorized Missing or invalid authentication
403 Forbidden Authenticated but insufficient permissions
404 Not Found Resource does not exist
409 Conflict Request conflicts with current state
422 Unprocessable Entity Valid syntax but semantic errors
429 Too Many Requests Rate limit exceeded (include Retry-After)
500 Internal Server Error Unexpected server failure
502 Bad Gateway Upstream returned invalid response
503 Service Unavailable Temporarily overloaded or maintenance

Standard Error Envelope

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request body contains invalid fields.",
    "details": [
      { "field": "email", "message": "Must be a valid email address" }
    ],
    "requestId": "req_abc123xyz"
  }
}

Graceful Degradation

Strategy Example
Fallback values Show cached avatar when image service is down
Feature flags Disable unstable recommendation engine
Cached responses Serve stale data with X-Cache: STALE header
Partial response Return available data with warnings array
async function getProductPage(productId) {
  const product = await productService.get(productId); // critical — propagate errors

  const [reviews, recommendations] = await Promise.allSettled([
    reviewService.getForProduct(productId),
    recommendationService.getForProduct(productId),
  ]);

  return {
    product,
    reviews: reviews.status === 'fulfilled' ? reviews.value : [],
    recommendations: recommendations.status === 'fulfilled' ? recommendations.value : [],
    warnings: [reviews, recommendations]
      .filter((r) => r.status === 'rejected')
      .map((r) => ({ service: 'degraded', reason: r.reason.message })),
  };
}

Logging & Monitoring

Practice Implementation
Structured logging JSON: level, message, error, requestId, userId, timestamp
Error tracking Sentry, Datadog, Bugsnag — automatic capture with source maps
Alert thresholds Error rate > 1%, P99 latency > 2s, 5xx spike
Correlation IDs Pass requestId through all service calls
Log levels error = needs attention, warn = degraded, info = normal, debug = dev

Anti-Patterns

Anti-Pattern Fix
Swallowing errors catch (e) {} Log and re-throw, or handle explicitly
Generic catch-all at every level Catch specific types, let unexpected errors bubble
Error as control flow Use conditionals, return values, or option types
Stringly-typed errors throw "wrong" Throw Error objects with codes and context
Logging and throwing Log at the boundary only, or wrap and re-throw
Catch-and-return-null Return Result type, throw, or return error object
Ignoring Promise rejections Always await or attach .catch()
Exposing internals Sanitize responses; log details server-side only

NEVER Do

  1. NEVER swallow errors silently — catch (e) {} hides bugs and causes silent data corruption
  2. NEVER expose stack traces, SQL errors, or file paths in API responses — log details server-side only
  3. NEVER use string throws — throw 'error' has no stack trace, no type, no context
  4. NEVER catch and return null without explanation — callers have no idea why the operation failed
  5. NEVER ignore unhandled Promise rejections — always await or attach .catch()
  6. NEVER cache error responses — 5xx and transient errors must not be cached and re-served
  7. NEVER use exceptions for normal control flow — exceptions are for exceptional conditions
  8. NEVER return generic "Something went wrong" without logging the real error — always log the full error server-side with request context

正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。

标签

error-handlingresiliencecircuit-breakerretry-patternobservabilityapi-designmicroservicesjavascriptpythongorust

同类 Skill