> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentwallex.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 오류 처리

> 오류 형식, 오류 유형, SDK 및 REST API에서 오류를 처리하는 방법을 설명합니다.

## 오류 형식

모든 AgentWallex API 오류는 일관된 JSON 형식을 따릅니다:

```json theme={null}
{
  "code": "invalid_request",
  "type": "invalid_request_error",
  "message": "human readable error description"
}
```

| 필드        | 설명                                                            |
| --------- | ------------------------------------------------------------- |
| `code`    | 기계 판독 가능한 오류 코드 (예: `policy_violation`, `insufficient_funds`) |
| `type`    | 오류 카테고리 (아래 표 참조)                                             |
| `message` | 사람이 읽을 수 있는 오류 설명                                             |

## 오류 유형

| 유형                      | HTTP 상태 | 설명                         |
| ----------------------- | ------- | -------------------------- |
| `invalid_request_error` | 400     | 요청 본문 또는 매개변수가 유효하지 않음     |
| `authentication_error`  | 401     | API 키 / 토큰이 누락되었거나 유효하지 않음 |
| `authorization_error`   | 403     | 유효한 자격 증명이지만 권한이 부족함       |
| `not_found_error`       | 404     | 요청한 리소스가 존재하지 않음           |
| `rate_limit_error`      | 429     | 요청이 너무 많음 — 표시된 지연 후 재시도   |
| `internal_error`        | 500     | 서버 측 오류 — 지속되면 지원팀에 문의     |

## 일반적인 오류 코드

| 코드                    | 유형                      | 설명                       |
| --------------------- | ----------------------- | ------------------------ |
| `policy_violation`    | `invalid_request_error` | 정책 엔진에 의해 거래가 차단됨        |
| `insufficient_funds`  | `invalid_request_error` | 거래에 대한 지갑 잔액이 부족함        |
| `agent_frozen`        | `invalid_request_error` | 에이전트가 동결됨 — 거래 전에 해제 필요  |
| `invalid_chain`       | `invalid_request_error` | 지원되지 않거나 유효하지 않은 체인 ID   |
| `invalid_token`       | `invalid_request_error` | 지정된 체인에서 지원되지 않는 토큰      |
| `invalid_address`     | `invalid_request_error` | 잘못된 형식의 수신자 주소           |
| `session_expired`     | `invalid_request_error` | x402 세션이 만료되었거나 예산을 초과함  |
| `rate_limit_exceeded` | `rate_limit_error`      | API 속도 제한 도달             |
| `approval_timeout`    | `invalid_request_error` | 제한 시간 내에 사람 승인이 이루어지지 않음 |

## SDK 오류 처리

### TypeScript

TypeScript SDK는 특정 오류 유형에 대한 타입화된 오류 클래스를 제공합니다:

```typescript theme={null}
import {
  AgentWallexError,
  PolicyViolationError,
} from "@agentwallex/sdk";

try {
  const tx = await aw.payments.send({
    agentId: "agent_abc123",
    to: "0xRecipientAddress",
    amount: "50.00",
    token: "USDC",
  });
} catch (error) {
  if (error instanceof PolicyViolationError) {
    console.log(`Policy violated: ${error.rule}`);
    console.log(`Details: ${error.message}`);
    // Handle: adjust amount, use different address, etc.
  } else if (error instanceof AgentWallexError) {
    console.log(`API error [${error.code}]: ${error.message}`);

    switch (error.code) {
      case "insufficient_funds":
        // Top up the wallet
        break;
      case "agent_frozen":
        // Unfreeze or use a different agent
        break;
      case "rate_limit_exceeded":
        // Wait and retry
        break;
      default:
        // Log and alert
        break;
    }
  } else {
    // Network error or unexpected exception
    console.error("Unexpected error:", error);
  }
}
```

### Python

```python theme={null}
from agentwallex import AgentWallexError, PolicyViolationError

try:
    tx = await aw.payments.send(
        agent_id="agent_abc123",
        to="0xRecipientAddress",
        amount="50.00",
        token="USDC",
    )
except PolicyViolationError as e:
    print(f"Policy violated: {e.rule}")
    print(f"Details: {e.message}")
except AgentWallexError as e:
    print(f"API error [{e.code}]: {e.message}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

## 재시도 전략

<Tip>
  재시도에는 지수 백오프를 사용하세요. `rate_limit_error` 및 `internal_error`에 대해서만 재시도하세요. `invalid_request_error` 또는 `authentication_error`는 재시도하지 마세요 — 요청을 수정해야 합니다.
</Tip>

```typescript theme={null}
async function withRetry<T>(
  fn: () => Promise<T>,
  maxRetries: number = 3
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (
        error instanceof AgentWallexError &&
        (error.type === "rate_limit_error" || error.type === "internal_error") &&
        attempt < maxRetries
      ) {
        const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
  throw new Error("Max retries exceeded");
}

// Usage
const tx = await withRetry(() =>
  aw.payments.send({
    agentId: "agent_abc123",
    to: "0xRecipientAddress",
    amount: "50.00",
    token: "USDC",
  })
);
```

## HTTP 상태 코드 레퍼런스

| 상태  | 의미      | 조치                                |
| --- | ------- | --------------------------------- |
| 200 | 성공      | 응답을 처리합니다                         |
| 201 | 생성됨     | 리소스가 성공적으로 생성되었습니다                |
| 400 | 잘못된 요청  | 요청 매개변수를 수정합니다                    |
| 401 | 인증되지 않음 | API 키를 확인합니다                      |
| 403 | 금지됨     | 권한 / 플랜 등급을 확인합니다                 |
| 404 | 찾을 수 없음 | 리소스 ID가 존재하는지 확인합니다               |
| 429 | 속도 제한됨  | 백오프를 적용하여 대기 후 재시도합니다             |
| 500 | 서버 오류   | 백오프를 적용하여 재시도합니다. 지속되면 지원팀에 문의합니다 |
