error-handling

error-handling

热门

适用于 TypeScript、Python 和 Go 的健壮错误处理模式。涵盖类型化错误、错误边界、重试机制、熔断器以及面向用户的错误提示设计。

24万Star
3.6万Fork
更新于 2026/8/2
SKILL.md
只读
名称
error-handling
描述

适用于 TypeScript、Python 和 Go 的健壮错误处理模式。涵盖类型化错误、错误边界、重试机制、熔断器以及面向用户的错误提示设计。

错误处理模式

适用于生产环境应用的一致且健壮的错误处理模式。

何时启用

  • 为新模块或服务设计错误类型或异常层级结构时
  • 为不可靠的外部依赖添加重试逻辑或熔断器时
  • 审查 API 接口是否存在缺失的错误处理时
  • 实现面向用户的错误提示与反馈时
  • 排查级联失效或错误被静默吞掉的问题时

核心原则

  1. 快速失败,显式抛出 — 在错误发生的边界立即暴露,绝不掩盖错误
  2. 优先使用类型化错误而非纯字符串 — 将结构化的错误视为一等公民
  3. 区分用户文案与开发者日志 — 给用户展示友好的提示,在服务端记录完整的上下文日志
  4. 绝不静默吞掉错误 — 每一个 catch 块都必须处理、重新抛出或记录日志
  5. 错误也是 API 契约的一部分 — 明确文档化客户端可能收到的每个错误码

TypeScript / JavaScript

类型化错误类

// 为你的业务领域定义错误层级结构
export class AppError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode: number = 500,
    public readonly details?: unknown,
  ) {
    super(message)
    this.name = this.constructor.name
    // 在转译后的 ES5 JavaScript 中保持正确的原型链。
    // 继承原生 Error 类时,这是保证 `instanceof` 检查(例如 `error instanceof NotFoundError`)
    // 正常工作所必需的。
    Object.setPrototypeOf(this, new.target.prototype)
  }
}

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

export class ValidationError extends AppError {
  constructor(message: string, details: { field: string; message: string }[]) {
    super(message, 'VALIDATION_ERROR', 422, details)
  }
}

export class UnauthorizedError extends AppError {
  constructor(reason = 'Authentication required') {
    super(reason, 'UNAUTHORIZED', 401)
  }
}

export class RateLimitError extends AppError {
  constructor(public readonly retryAfterMs: number) {
    super('Rate limit exceeded', 'RATE_LIMITED', 429)
  }
}

Result 模式(无抛出风格)

适用于失败属于预期内且较为常见的操作场景(如数据解析、外部接口调用):

type Result<T, E = AppError> =
  | { ok: true; value: T }
  | { ok: false; error: E }

function ok<T>(value: T): Result<T> {
  return { ok: true, value }
}

function err<E>(error: E): Result<never, E> {
  return { ok: false, error }
}

// 使用示例
async function fetchUser(id: string): Promise<Result<User>> {
  try {
    const user = await db.users.findUnique({ where: { id } })
    if (!user) return err(new NotFoundError('User', id))
    return ok(user)
  } catch (e) {
    return err(new AppError('Database error', 'DB_ERROR'))
  }
}

const result = await fetchUser('abc-123')
if (!result.ok) {
  // 此处 TypeScript 能收窄类型并识别出 result.error
  logger.error('Failed to fetch user', { error: result.error })
  return
}
// 此处 TypeScript 能收窄类型并识别出 result.value
console.log(result.value.email)

API 错误处理器(Next.js / Express)

import { NextRequest, NextResponse } from 'next/server'

function handleApiError(error: unknown): NextResponse {
  // 已知的应用业务错误
  if (error instanceof AppError) {
    return NextResponse.json(
      {
        error: {
          code: error.code,
          message: error.message,
          ...(error.details ? { details: error.details } : {}),
        },
      },
      { status: error.statusCode },
    )
  }

  // Zod 参数校验错误
  if (error instanceof z.ZodError) {
    return NextResponse.json(
      {
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Request validation failed',
          details: error.issues.map(i => ({
            field: i.path.join('.'),
            message: i.message,
          })),
        },
      },
      { status: 422 },
    )
  }

  // 未预期的未知错误 — 记录完整日志,返回通用错误提示
  console.error('Unexpected error:', error)
  return NextResponse.json(
    { error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } },
    { status: 500 },
  )
}

export async function POST(req: NextRequest) {
  try {
    // ... 处理逻辑
  } catch (error) {
    return handleApiError(error)
  }
}

React 错误边界

import { Component, ErrorInfo, ReactNode } from 'react'

interface Props {
  fallback: ReactNode
  onError?: (error: Error, info: ErrorInfo) => void
  children: ReactNode
}

interface State {
  hasError: boolean
  error: Error | null
}

export class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false, error: null }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    this.props.onError?.(error, info)
    console.error('Unhandled React error:', error, info)
  }

  render() {
    if (this.state.hasError) return this.props.fallback
    return this.props.children
  }
}

// 使用示例
<ErrorBoundary fallback={<p>Something went wrong. Please refresh.</p>}>
  <MyComponent />
</ErrorBoundary>

Python

自定义异常层级结构

class AppError(Exception):
    """应用基础错误类。"""
    def __init__(self, message: str, code: str, status_code: int = 500):
        super().__init__(message)
        self.code = code
        self.status_code = status_code

class NotFoundError(AppError):
    def __init__(self, resource: str, id: str):
        super().__init__(f"{resource} not found: {id}", "NOT_FOUND", 404)

class ValidationError(AppError):
    def __init__(self, message: str, details: list[dict] | None = None):
        super().__init__(message, "VALIDATION_ERROR", 422)
        self.details = details or []

FastAPI 全局异常处理器

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": {"code": exc.code, "message": str(exc)}},
    )

@app.exception_handler(Exception)
async def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:
    # 记录详细日志,返回通用错误提示
    logger.exception("Unexpected error", exc_info=exc)
    return JSONResponse(
        status_code=500,
        content={"error": {"code": "INTERNAL_ERROR", "message": "An unexpected error occurred"}},
    )

Go

哨兵错误与错误包装

package domain

import "errors"

// 用于类型检查的哨兵错误 (Sentinel errors)
var (
    ErrNotFound    = errors.New("not found")
    ErrUnauthorized = errors.New("unauthorized")
    ErrConflict     = errors.New("conflict")
)

// 使用上下文包装错误 — 绝不丢失底层原始错误
func (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {
    user, err := r.db.QueryRow(ctx, "SELECT * FROM users WHERE id = $1", id)
    if errors.Is(err, sql.ErrNoRows) {
        return nil, fmt.Errorf("user %s: %w", id, ErrNotFound)
    }
    if err != nil {
        return nil, fmt.Errorf("querying user %s: %w", id, err)
    }
    return user, nil
}

// 在 Handler 层拆包以决定对应的响应
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
    user, err := h.service.GetUser(r.Context(), chi.URLParam(r, "id"))
    if err != nil {
        switch {
        case errors.Is(err, domain.ErrNotFound):
            writeError(w, http.StatusNotFound, "not_found", err.Error())
        case errors.Is(err, domain.ErrUnauthorized):
            writeError(w, http.StatusForbidden, "forbidden", "Access denied")
        default:
            slog.Error("unexpected error", "err", err)
            writeError(w, http.StatusInternalServerError, "internal_error", "An unexpected error occurred")
        }
        return
    }
    writeJSON(w, http.StatusOK, user)
}

带指数退避的重试机制

interface RetryOptions {
  maxAttempts?: number
  baseDelayMs?: number
  maxDelayMs?: number
  retryIf?: (error: unknown) => boolean
}

async function withRetry<T>(
  fn: () => Promise<T>,
  options: RetryOptions = {},
): Promise<T> {
  const {
    maxAttempts = 3,
    baseDelayMs = 500,
    maxDelayMs = 10_000,
    retryIf = () => true,
  } = options

  let lastError: unknown

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn()
    } catch (error) {
      lastError = error
      if (attempt === maxAttempts || !retryIf(error)) throw error

      const jitter = Math.random() * baseDelayMs
      const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs)
      await new Promise(resolve => setTimeout(resolve, delay))
    }
  }

  throw lastError
}

// 使用示例:重试瞬时网络错误,但不重试 4xx 客户端错误
const data = await withRetry(() => fetch('/api/data').then(r => r.json()), {
  maxAttempts: 3,
  retryIf: (error) => !(error instanceof AppError && error.statusCode < 500),
})

面向用户的错误提示设计

将错误码映射为易读的用户提示,避免在前端展示技术细节。

const USER_ERROR_MESSAGES: Record<string, string> = {
  NOT_FOUND: 'The requested item could not be found.',
  UNAUTHORIZED: 'Please sign in to continue.',
  FORBIDDEN: "You don't have permission to do that.",
  VALIDATION_ERROR: 'Please check your input and try again.',
  RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',
  INTERNAL_ERROR: 'Something went wrong on our end. Please try again later.',
}

export function getUserMessage(code: string): string {
  return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR
}

错误处理自查清单

合并任何涉及错误处理的代码之前:

  • [ ] 每一个 catch 块都进行了处理、重新抛出或记录日志 — 没有任何静默吞掉
  • [ ] API 错误均遵循统一的外包结构 { error: { code, message } }
  • [ ] 面向用户的错误提示绝不包含调用栈(stack trace)或内部实现细节
  • [ ] 服务端完整记录了错误的上下文信息
  • [ ] 自定义错误类均继承自 AppError 基类,且包含 code 字段
  • [ ] 异步函数已将错误正确透传给调用方 — 没有未处理的、无兜底机制的 fire-and-forget
  • [ ] 重试逻辑仅对可重试的错误生效(排除 4xx 客户端错误)
  • [ ] 用于渲染的 React 组件已被 ErrorBoundary 包裹