MeWrite Docs

AWS S3: NoSuchKey

AWS S3でオブジェクトが存在しない場合のエラー

概要

AWS S3で指定したキー(オブジェクトパス)が存在しない場合に発生するエラーです。

エラーメッセージ

An error occurred (NoSuchKey) when calling the GetObject operation: The specified key does not exist.

または

1
2
3
4
5
<Error>
  <Code>NoSuchKey</Code>
  <Message>The specified key does not exist.</Message>
  <Key>path/to/object.txt</Key>
</Error>

原因

  1. キーの誤り: パスやファイル名のタイポ
  2. オブジェクト未作成: アップロードされていない
  3. 削除済み: オブジェクトが削除された
  4. バージョニング: 特定バージョンが存在しない

解決策

1. キーの存在確認

1
2
3
4
5
6
7
# オブジェクトの存在確認
aws s3api head-object \
  --bucket mybucket \
  --key path/to/object.txt

# リスト表示で確認
aws s3 ls s3://mybucket/path/to/

2. 正しいキー形式

1
2
3
4
5
6
7
8
# 悪い例:先頭にスラッシュ
aws s3 cp s3://mybucket//path/to/file.txt .

# 良い例
aws s3 cp s3://mybucket/path/to/file.txt .

# 大文字小文字は区別される
# s3://mybucket/File.txt と s3://mybucket/file.txt は別物

3. エラーハンドリング(Python)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')

def get_object_safely(bucket, key):
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        return response['Body'].read()
    except ClientError as e:
        if e.response['Error']['Code'] == 'NoSuchKey':
            print(f"オブジェクトが存在しません: {key}")
            return None
        raise

4. エラーハンドリング(JavaScript)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');

const client = new S3Client({});

async function getObjectSafely(bucket, key) {
  try {
    const command = new GetObjectCommand({ Bucket: bucket, Key: key });
    const response = await client.send(command);
    return response.Body;
  } catch (error) {
    if (error.name === 'NoSuchKey') {
      console.log(`オブジェクトが存在しません: ${key}`);
      return null;
    }
    throw error;
  }
}

5. headObject で事前確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def object_exists(bucket, key):
    try:
        s3.head_object(Bucket=bucket, Key=key)
        return True
    except ClientError as e:
        if e.response['Error']['Code'] == '404':
            return False
        raise

if object_exists('mybucket', 'path/to/file.txt'):
    # オブジェクトを取得
    pass

6. バージョニング確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# バージョン一覧を取得
aws s3api list-object-versions \
  --bucket mybucket \
  --prefix path/to/object.txt

# 特定バージョンを取得
aws s3api get-object \
  --bucket mybucket \
  --key path/to/object.txt \
  --version-id "abc123" \
  output.txt

7. 削除マーカーの確認

1
2
3
4
5
# 削除マーカーがあるか確認
aws s3api list-object-versions \
  --bucket mybucket \
  --prefix path/to/object.txt \
  --query 'DeleteMarkers'

8. プレフィックスでリスト取得

1
2
3
4
5
# 特定プレフィックスのオブジェクト一覧
paginator = s3.get_paginator('list_objects_v2')
for page in paginator.paginate(Bucket='mybucket', Prefix='path/to/'):
    for obj in page.get('Contents', []):
        print(obj['Key'])

9. 署名付きURLの有効期限

1
2
3
4
5
6
7
# 署名付きURLを生成
url = s3.generate_presigned_url(
    'get_object',
    Params={'Bucket': 'mybucket', 'Key': 'path/to/file.txt'},
    ExpiresIn=3600  # 1時間有効
)
# 有効期限切れ後はエラー

よくある間違い

  • URLエンコードされたキー(スペースが%20になる)
  • Windows形式のパス区切り(\ではなく/を使用)
  • バケット名とキーの混同
  • レプリケーション遅延でオブジェクトがまだコピーされていない

AWS の他のエラー

最終更新: 2025-12-09