Skip to content

JSONパース失敗時のエラーハンドリング不足 (POST /articles) #11

Description

@claude

🔴 エラー概要

POST /articles エンドポイントで不正な JSON を送信した際、適切なエラーハンドリングが行われず、500 Internal Server Error が発生しています。JSON パース処理で SyntaxError が発生し、クライアントに有用なエラーメッセージが返されていません。

🔍 根本原因

  • 問題箇所: src/lambda/sample-app/index.ts:192
  • 原因: createArticle 関数内で JSON.parse(event.body || '{}') を実行する際、不正な JSON 文字列が渡された場合の例外処理が実装されていません。そのため、パースエラーが発生すると関数外の catch ブロックに到達し、500 エラーとして返されます。
  • コードの問題:
// src/lambda/sample-app/index.ts:191-193
const createArticle = (event: APIGatewayProxyEvent): APIGatewayProxyResult => {
    const body = JSON.parse(event.body || '{}');  // ← エラーハンドリングなし
    const { title, content, authorId, tags } = body;

同様の問題は updateArticle (224行目) と createComment (256行目) にも存在します。

📊 影響範囲

  • 影響を受ける機能:
    • POST /articles (記事作成)
    • PUT /articles/:id (記事更新)
    • POST /articles/:id/comments (コメント投稿)
  • 影響を受けるユーザー:
    • API クライアント開発者 (不正な JSON を送信した場合、具体的なエラー原因が分からない)
    • フロントエンド開発者 (バグやネットワークエラーでリクエストボディが破損した場合)
  • 深刻度: Medium
    • データ損失やセキュリティ問題は発生しないが、ユーザー体験とデバッグ効率に影響

🛠️ 修正方法

各関数で JSON パース処理を try-catch でラップし、400 Bad Request として適切なエラーメッセージを返すようにします。

// src/lambda/sample-app/index.ts:191-204
const createArticle = (event: APIGatewayProxyEvent): APIGatewayProxyResult => {
    let body;
    try {
        body = JSON.parse(event.body || '{}');
    } catch (error) {
        return createErrorResponse(400, 'ART-005', 'リクエストボディが不正なJSON形式です', {
            error: (error as Error).message,
        });
    }
    
    const { title, content, authorId, tags } = body;

    // バリデーション
    if (!title || !content || !authorId) {
        return createErrorResponse(400, 'ART-003', '記事の作成に失敗しました', {
            missingFields: [
                !title && 'title',
                !content && 'content',
                !authorId && 'authorId',
            ].filter(Boolean),
        });
    }
    // ... 以降は既存のコード

同様の修正を updateArticlecreateComment にも適用してください。

🚀 再発防止策

  • 共通ユーティリティ関数の作成: JSON パース処理を共通化し、エラーハンドリングを一箇所で管理
    const parseRequestBody = (body: string | null): any => {
        try {
            return JSON.parse(body || '{}');
        } catch (error) {
            throw new Error('INVALID_JSON');
        }
    }
  • 入力バリデーションライブラリの導入: Zod や Joi などのスキーマバリデーションライブラリを使用し、型安全性とエラーメッセージの品質を向上
  • 統合テストの追加: 不正な JSON を送信するテストケースを追加し、適切なエラーレスポンスが返ることを確認

📝 検知情報

エラータイプ: SyntaxError
エラーメッセージ: Unexpected token 'i', "invalid json" is not valid JSON
発生時刻: 2025-11-27T08:30:07.013Z
コンテキスト: POST /articles
ログソース: /aws/lambda/llm-ops-sample-app
スタックトレース
SyntaxError: Unexpected token 'i', "invalid json" is not valid JSON
    at JSON.parse (<anonymous>)
    at createArticle (/var/task/index.js:148:23)
    at Runtime.handler (/var/task/index.js:245:20)
    at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1306:29)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions