← 中文资源

简体中文版本

生产应用错误处理模式

对错误分类、携带上下文传播、在不泄露密钥的前提下记录与追踪,并设计让生产继续运行的恢复路径。

阅读英文原文

引言

错误处理的目标不是消灭所有异常,而是让失败可理解、可恢复、可追溯。最糟的模式是捕获后静默忽略,或把内部细节直接返回给用户。

先分类

区分用户错误、业务规则冲突、依赖失败、超时、程序缺陷和资源耗尽。可重试与不可重试、可降级与不可降级需要不同处理。分类决定了是否重试、返回什么状态码、是否告警。

带上下文传播

在边界包装错误,附上操作名、资源 id 和 request id,但不要泄露密钥。使用错误链保留原因,避免把底层异常转成无信息的字符串。

顶层处理

在请求边界统一记录、转换为稳定响应并决定是否退出进程。程序缺陷和未知状态应让请求失败并上报,而不是继续运行。响应只暴露安全的错误码和消息。

恢复与观测

对可降级路径返回缓存或默认值,并标记降级。结构化日志记录错误类别和堆栈,敏感字段脱敏。前端使用错误边界隔离组件失败。用错误预算驱动告警,避免逐条异常告警。

结论

好的错误处理让用户得到清晰反馈,让运维得到足够上下文,让系统在可恢复时继续运行。

代码示例

class AppError extends Error {
  constructor(message: string, public readonly kind: string, public readonly retryable: boolean, public readonly statusCode: number, public readonly context?: Record<string, unknown>) {
    super(message);
    this.name = this.constructor.name;
  }
}

class ValidationError extends AppError {
  constructor(message: string, context?: Record<string, unknown>) { super(message, "validation", false, 422, context); }
}
class NotFoundError extends AppError {
  constructor(resource: string, id: string) { super(`${resource} not found`, "not_found", false, 404, { resource, id }); }
}
class TransientError extends AppError {
  constructor(message: string, context?: Record<string, unknown>) { super(message, "transient", true, 503, context); }
}
class ConfigurationError extends AppError {
  constructor(message: string) { super(message, "configuration", false, 500); }
}
class WrappedError extends Error {
  constructor(message: string, public readonly cause: unknown, public readonly context?: Record<string, unknown>) {
    super(message);
    this.name = "WrappedError";
  }
}

async function getUser(id: string) {
  try {
    const res = await fetch(`/billing/users/${id}`, { signal: AbortSignal.timeout(2000) });
    if (!res.ok) throw new AppError(`billing returned ${res.status}`, "http", res.status >= 500, res.status, { id });
    return await res.json();
  } catch (err) {
    throw new WrappedError("fetching user from billing", err, { id, service: "billing" });
  }
}
function errorHandler(err: unknown, req: Request, res: Response, next: NextFunction) {
  const appErr = err instanceof AppError ? err : new AppError("unexpected error", "internal", false, 500);
  const logEntry = {
    level: appErr.statusCode >= 500 ? "error" : "warn",
    message: err instanceof Error ? err.message : String(err),
    kind: appErr.kind,
    statusCode: appErr.statusCode,
    requestId: req.id,
    userId: req.user?.id,
    path: req.path,
    context: appErr.context,
    stack: appErr.statusCode >= 500 ? (err instanceof Error ? err.stack : undefined) : undefined,
  };
  logger.log(logEntry);
  res.status(appErr.statusCode).json({
    error: clientMessage(appErr),
    requestId: req.id,
  });
}

function clientMessage(err: AppError): string {
  // Never expose internal details for 5xx; the client cannot act on them.
  if (err.statusCode >= 500) return "Something went wrong. We have been notified.";
  return err.message;
}
const SENSITIVE = new Set(["password", "authorization", "token", "secret", "cookie"]);
function redact(obj: unknown): unknown {
  if (typeof obj !== "object" || obj === null) return obj;
  return Object.fromEntries(Object.entries(obj as Record<string, unknown>).map(([k, v]) =>
    [k, SENSITIVE.has(k.toLowerCase()) ? "[redacted]" : redact(v)]
  ));
}
async function getProductPage(id: string) {
  const product = await getProduct(id); // required; if this fails, the page fails
  let recommendations: Product[] = [];
  try {
    recommendations = await recommendationsService.get(id);
  } catch (err) {
    logger.warn({ msg: "recommendations failed, rendering without", id, err: toLoggable(err) });
    recommendations = await cache.get(`recs:${id}`) ?? []; // stale cache or empty
  }
  return { product, recommendations };
}
class ErrorBoundary extends React.Component<{ fallback: React.ReactNode; children: React.ReactNode }, { error: Error | null }> {
  state = { error: null as Error | null };
  static getDerivedStateFromError(error: Error) { return { error }; }
  componentDidCatch(error: Error, info: React.ErrorInfo) {
    logger.error({ msg: "UI render error", error: toLoggable(error), componentStack: info.componentStack });
  }
  render() {
    return this.state.error ? this.props.fallback : this.props.children;
  }
}

// Wrap each route so a failure is confined.
<ErrorBoundary fallback={<RegionError onRetry={() => location.reload()} />}>
  <ProductPage />
</ErrorBoundary>
// Compute the error budget burn rate from metrics.
async function burnRate(service: string, window: string): Promise<number> {
  const errors = await metrics.count({ service, status: "5xx", window });
  const total = await metrics.count({ service, window });
  const observedRate = errors / total;
  const budgetRate = 0.01; // 1% SLO
  return observedRate / budgetRate; // 1.0 = consuming at exactly the budget rate
}
// burnRate > 1 for a sustained window -> freeze deploys; > 14 over 1h -> page.