> ## Documentation Index
> Fetch the complete documentation index at: https://supertone-b89202c8.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# エラー処理

> Supertone APIが返すHTTPステータスコード、その原因、本番コードでの適切な対応。

> [!NOTE]
>
> このドキュメントは英語の原文から自動翻訳されています。表現に不自然な箇所がある場合があります。正確な内容は[英語の原文](/en/docs/production/error-handling)もあわせてご確認ください。

Supertone APIは標準的なHTTPステータスコードを使用します。エラーは問題を説明するJSONボディを返し、SDKはそれをキャッチして処理できる型付き例外として公開します。

## ステータスコードリファレンス

| Status | Meaning | Most common cause |
| - | - | - |
| `200 OK` | 成功 | — |
| `400 Bad Request` | 不正なリクエスト | 必須フィールドの欠落、無効なenum値、`text`が300文字を超える（生のAPIのみ）、`voice_settings`が範囲外。 |
| `401 Unauthorized` | 認証失敗 | `x-sup-api-key`が欠落または無効。 |
| `402 Payment Required` | クレジット不足 | クレジット残高がゼロ、またはリクエストに対して不足している。 |
| `403 Forbidden` | 権限なし | 別のアカウントが所有するカスタムボイスを呼び出そうとした、または権限のないキーを使用している。 |
| `404 Not Found` | リソースが存在しない | 誤った`voice_id`、エンドポイントパスのタイプミス。 |
| `408 Request Timeout` | サーバーが時間内に処理できなかった | 一時的なエラー。リトライしてください。 |
| `413 Payload Too Large` | アップロードが大きすぎる | ボイスクローン音声が3 MBを超えている。 |
| `415 Unsupported Media Type` | アップロード形式が不正 | ボイスクローン音声がWAV/MP3ではない。 |
| `429 Too Many Requests` | レート制限超過 | [レート制限](/ja/docs/production/rate-limits)を参照してください。 |
| `500 Internal Server Error` | サーバー側の問題 | 通常は一時的なものです。バックオフを伴うリトライを行ってください。 |

## SDKのエラークラス

両方のSDKは各ステータスコードを型付きエラークラスにマッピングします。文字列を解析するよりも、特定のクラスをキャッチする方がクリーンです。

**Python**

```python theme={"dark"}
from supertone import errors

try:
    response = client.text_to_speech.create_speech(...)
except errors.BadRequestErrorResponse as e:
    # 400 — fix the request
    log.error("Bad request: %s", e.message)
except errors.UnauthorizedErrorResponse:
    # 401 — re-check the API key
    rotate_key_and_retry()
except errors.PaymentRequiredErrorResponse:
    # 402 — alert the user / billing system
    notify_low_credits()
except errors.ForbiddenErrorResponse:
    # 403 — wrong voice for this account
    fallback_to_preset_voice()
except errors.TooManyRequestsErrorResponse:
    # 429 — back off and retry
    backoff_and_retry()
except errors.InternalServerErrorResponse:
    # 500 — retry transient failure
    retry_with_backoff()
except errors.SupertoneError as e:
    # Any other API-level error
    log.exception("Supertone API error: %s", e.message)
```

**TypeScript**

```typescript theme={"dark"}
import * as errors from "@supertone/supertone/models/errors";

try {
  const response = await client.textToSpeech.createSpeech({ /* ... */ });
} catch (err) {
  if (err instanceof errors.BadRequestErrorResponse) {
    console.error("Bad request:", err.message);
  } else if (err instanceof errors.UnauthorizedErrorResponse) {
    rotateKeyAndRetry();
  } else if (err instanceof errors.PaymentRequiredErrorResponse) {
    notifyLowCredits();
  } else if (err instanceof errors.ForbiddenErrorResponse) {
    fallbackToPresetVoice();
  } else if (err instanceof errors.TooManyRequestsErrorResponse) {
    await backoffAndRetry();
  } else if (err instanceof errors.InternalServerErrorResponse) {
    await retryWithBackoff();
  } else if (err instanceof errors.SupertoneError) {
    console.error(`HTTP ${err.statusCode}: ${err.message}`);
  } else {
    throw err;
  }
}
```

すべてのSDKエラーは以下を公開します。

| Property | Description |
| - | - |
| `message` | サーバーから提供されるエラーメッセージ。 |
| `status_code` / `statusCode` | HTTPステータスコード。 |
| `headers` | レスポンスヘッダー。 |
| `body` | 生のレスポンスボディ文字列。 |
| `raw_response` / `rawResponse` | 基底のHTTPレスポンスオブジェクト。 |

## 各エラーへの対応

### 4xx — クライアント側

| Code | Recommended response |
| - | - |
| `400` | リトライしない。リクエストボディをログに記録し、スキーマの不一致を修正してください。 |
| `401` | キーの値、コンソールでのキーの有効化、および`x-sup-api-key`ヘッダーがプロキシで取り除かれていないかを確認してください。 |
| `402` | 「クレジット不足」をユーザーに通知し、課金ページへリンクし、ワークフローを停止してください。クレジットを追加せずにリトライしても再度失敗します。 |
| `403` | ボイスがこのアカウントに属していることを確認してください。カスタムボイスはアカウント単位です。 |
| `404` | `GET /v1/voices`または`GET /v1/custom-voices`を呼び出して、`voice_id`が存在することを確認してください。 |
| `413` | アップロードサイズを縮小してください。モノラルへの再エンコード、ビットレートの低減、または3 MB未満へのトリミングを行います。 |
| `415` | アップロードをWAVまたはMP3として再エンコードしてください。 |
| `429` | [リトライとバックオフ](/ja/docs/production/retries-and-backoff)を参照してください。 |

### 5xx — サーバー側

| Code | Recommended response |
| - | - |
| `408` | リトライしてください。通常は一時的です。 |
| `500` | 指数バックオフを伴うリトライを行ってください。失敗が継続する場合（5分以上）は[サポートにお問い合わせ](/ja/docs/resources/support)ください。 |

## よくある落とし穴

* POSTリクエストで\*\*`Content-Type: application/json`が欠落\*\*していると`400`になります。
* **先頭/末尾に空白が含まれるAPIキー**（コピー＆ペースト時によく発生）は`401`になります。
* 「IDを知っている」場合でも、**別のアカウントからカスタムボイスを呼び出す**と`403`になります。
* 生のAPIに**300文字を超える`text`を送信**すると`400`になります。長いテキストを自動チャンク分割するにはSDKを使用してください。

## 関連項目

> **[リトライとバックオフ](/ja/docs/production/retries-and-backoff)**
>
> `429`および`5xx`に対する適切なリトライポリシー。

> **[レート制限](/ja/docs/production/rate-limits)**
>
> アカウントティア別の制限。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.