> ## 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.

# Xử lý Lỗi

> Định dạng lỗi, loại lỗi và cách xử lý lỗi trong SDK và REST API.

## Định dạng Lỗi

Tất cả lỗi API AgentWallex tuân theo định dạng JSON nhất quán:

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

| Trường    | Mô tả                                                                 |
| --------- | --------------------------------------------------------------------- |
| `code`    | Mã lỗi máy đọc được (ví dụ: `policy_violation`, `insufficient_funds`) |
| `type`    | Danh mục lỗi (xem bảng bên dưới)                                      |
| `message` | Mô tả con người đọc được về điều gì đã xảy ra sai                     |

## Các Loại Lỗi

| Loại                    | Mã HTTP | Mô tả                                              |
| ----------------------- | ------- | -------------------------------------------------- |
| `invalid_request_error` | 400     | Nội dung yêu cầu hoặc tham số không hợp lệ         |
| `authentication_error`  | 401     | Thiếu hoặc khóa API / token không hợp lệ           |
| `authorization_error`   | 403     | Thông tin xác thực hợp lệ nhưng không đủ quyền     |
| `not_found_error`       | 404     | Tài nguyên được yêu cầu không tồn tại              |
| `rate_limit_error`      | 429     | Quá nhiều yêu cầu — thử lại sau thời gian chỉ định |
| `internal_error`        | 500     | Lỗi phía server — liên hệ hỗ trợ nếu kéo dài       |

## Mã Lỗi Phổ biến

| Mã                    | Loại                    | Mô tả                                                    |
| --------------------- | ----------------------- | -------------------------------------------------------- |
| `policy_violation`    | `invalid_request_error` | Giao dịch bị chặn bởi công cụ chính sách                 |
| `insufficient_funds`  | `invalid_request_error` | Số dư ví quá thấp cho giao dịch                          |
| `agent_frozen`        | `invalid_request_error` | Tác nhân bị đóng băng — mở đóng băng trước khi giao dịch |
| `invalid_chain`       | `invalid_request_error` | Chain ID không được hỗ trợ hoặc không hợp lệ             |
| `invalid_token`       | `invalid_request_error` | Token không được hỗ trợ trên chuỗi được chỉ định         |
| `invalid_address`     | `invalid_request_error` | Địa chỉ người nhận không đúng định dạng                  |
| `session_expired`     | `invalid_request_error` | Phiên x402 đã hết hạn hoặc vượt ngân sách                |
| `rate_limit_exceeded` | `rate_limit_error`      | Đã đạt giới hạn tốc độ API                               |
| `approval_timeout`    | `invalid_request_error` | Phê duyệt con người không được cấp trong thời gian chờ   |

## Xử lý Lỗi SDK

### TypeScript

SDK TypeScript cung cấp các lớp lỗi có kiểu cho các loại lỗi cụ thể:

```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}")
```

## Chiến lược Thử lại

<Tip>
  Sử dụng backoff theo cấp số nhân cho việc thử lại. Chỉ thử lại với `rate_limit_error` và `internal_error`. Không thử lại `invalid_request_error` hoặc `authentication_error` — những lỗi đó yêu cầu sửa yêu cầu.
</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",
  })
);
```

## Tham chiếu Mã trạng thái HTTP

| Trạng thái | Ý nghĩa            | Hành động                                       |
| ---------- | ------------------ | ----------------------------------------------- |
| 200        | Thành công         | Xử lý phản hồi                                  |
| 201        | Đã tạo             | Tài nguyên được tạo thành công                  |
| 400        | Yêu cầu sai        | Sửa tham số yêu cầu                             |
| 401        | Chưa xác thực      | Kiểm tra khóa API                               |
| 403        | Bị cấm             | Kiểm tra quyền / cấp gói                        |
| 404        | Không tìm thấy     | Xác minh ID tài nguyên tồn tại                  |
| 429        | Bị giới hạn tốc độ | Chờ và thử lại với backoff                      |
| 500        | Lỗi Server         | Thử lại với backoff; liên hệ hỗ trợ nếu kéo dài |
