mcpField
A
api-error-handling

api-error-handling

github.com/secondsky开发240449 次安装5 周前更新
代码仓库

关于 api-error-handling

用于设计一致的 API 错误响应并处理 Node.js 和 Python Flask 中故障的开发技能,涵盖追踪、日志、重试和熔断器。

主要功能

  1. 01标准化错误响应结构
  2. 02Node.js ApiError 类
  3. 03熔断器模式
  4. 04Flask 异常与恢复
  5. 05指数退避重试
  6. 06错误日志与追踪指南

适用场景

  1. 01统一 API 端点的错误格式
  2. 02在错误响应中加入请求 ID
  3. 03处理下游服务反复故障
  4. 04配置 Flask 错误处理

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/secondsky/claude-skills --skill api-error-handling

安装后在 Claude Code 中输入/api-error-handling确认已加载。

附带文件references/python-flask.md

详细介绍

API 错误处理

通过标准化响应和恰当的日志记录,实现健壮的错误处理。

标准错误响应格式

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request parameters",
    "status": 400,
    "requestId": "req_abc123",
    "timestamp": "2025-01-15T10:30:00Z",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}

错误类(Node.js)

class ApiError extends Error {
  constructor(code, message, status = 500, details = null) {
    super(message);
    this.code = code;
    this.status = status;
    this.details = details;
  }

  static badRequest(message, details) {
    return new ApiError('BAD_REQUEST', message, 400, details);
  }

  static notFound(resource) {
    return new ApiError('NOT_FOUND', `${resource} not found`, 404);
  }

  static unauthorized() {
    return new ApiError('UNAUTHORIZED', 'Authentication required', 401);
  }
}

// Global error handler
app.use((err, req, res, next) => {
  const status = err.status || 500;
  const response = {
    error: {
      code: err.code || 'INTERNAL_ERROR',
      message: status === 500 ? 'Internal server error' : err.message,
      status,
      requestId: req.id
    }
  };

  if (err.details) response.error.details = err.details;
  if (status >= 500) logger.error(err);

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

熔断器模式

class CircuitBreaker {
  constructor(threshold = 5, timeout = 30000) {
    this.failures = 0;
    this.threshold = threshold;
    this.timeout = timeout;
    this.state = 'CLOSED';
  }

  async call(fn) {
    if (this.state === 'OPEN') throw new Error('Circuit open');
    try {
      const result = await fn();
      this.failures = 0;
      return result;
    } catch (err) {
      this.failures++;
      if (this.failures >= this.threshold) {
        this.state = 'OPEN';
        setTimeout(() => this.state = 'HALF_OPEN', this.timeout);
      }
      throw err;
    }
  }
}

其他实现

请参阅 references/python-flask.md,了解:

  • 使用自定义异常处理 Python Flask 错误
  • 支持自动恢复的熔断器
  • 使用指数退避重试
  • Sentry 集成

最佳实践

  • 在所有端点使用一致的错误格式
  • 包含请求 ID,以便追踪
  • 根据适当的严重级别记录错误
  • 切勿向客户端暴露堆栈跟踪
  • 区分客户端错误(4xx)和服务端错误(5xx)
  • 提供可执行的错误消息

评论

支持 Markdown