api-error-handling について
一貫した API エラーレスポンスの設計と、Node.js および Python Flask での障害処理を支援する開発スキルです。追跡、ログ、リトライ、サーキットブレーカーを扱います。
主な機能
- 01標準エラーレスポンス形式
- 02Node.js ApiError クラス
- 03サーキットブレーカーパターン
- 04Flask の例外と復旧
- 05指数バックオフによるリトライ
- 06エラーログと追跡の指針
活用シーン
- 01API エンドポイント間のエラー形式統一
- 02エラーレスポンスへのリクエスト ID 追加
- 03下流サービスの連続障害への対応
- 04Flask のエラー処理設定
インストール
コマンドをコピーしてターミナルで実行します。
$
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 対応