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

# Error Handling

> Error format, error types, and how to handle errors in the SDK and REST API.

## Error Format

All AgentWallex API errors follow a consistent JSON format:

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

| Field     | Description                                                                  |
| --------- | ---------------------------------------------------------------------------- |
| `code`    | Machine-readable error code (e.g., `policy_violation`, `insufficient_funds`) |
| `type`    | Error category (see table below)                                             |
| `message` | Human-readable description of what went wrong                                |

## Error Types

| Type                    | HTTP Status | Description                                         |
| ----------------------- | ----------- | --------------------------------------------------- |
| `invalid_request_error` | 400         | The request body or parameters are invalid          |
| `authentication_error`  | 401         | Missing or invalid API key / token                  |
| `authorization_error`   | 403         | Valid credentials but insufficient permissions      |
| `not_found_error`       | 404         | The requested resource does not exist               |
| `rate_limit_error`      | 429         | Too many requests — retry after the indicated delay |
| `internal_error`        | 500         | Server-side error — contact support if persistent   |

## Common Error Codes

| Code                  | Type                    | Description                                       |
| --------------------- | ----------------------- | ------------------------------------------------- |
| `policy_violation`    | `invalid_request_error` | Transaction blocked by policy engine              |
| `insufficient_funds`  | `invalid_request_error` | Wallet balance too low for the transaction        |
| `agent_frozen`        | `invalid_request_error` | Agent is frozen — unfreeze before transacting     |
| `invalid_chain`       | `invalid_request_error` | Unsupported or invalid chain ID                   |
| `invalid_token`       | `invalid_request_error` | Token not supported on the specified chain        |
| `invalid_address`     | `invalid_request_error` | Malformed recipient address                       |
| `session_expired`     | `invalid_request_error` | x402 session has expired or exceeded budget       |
| `rate_limit_exceeded` | `rate_limit_error`      | API rate limit reached                            |
| `approval_timeout`    | `invalid_request_error` | Human approval was not granted within the timeout |

## SDK Error Handling

### TypeScript

The TypeScript SDK provides typed error classes for specific error types:

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

## Retry Strategy

<Tip>
  Use exponential backoff for retries. Only retry on `rate_limit_error` and `internal_error`. Do not retry `invalid_request_error` or `authentication_error` — those require fixing the request.
</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 Status Code Reference

| Status | Meaning      | Action                                            |
| ------ | ------------ | ------------------------------------------------- |
| 200    | Success      | Process the response                              |
| 201    | Created      | Resource was created successfully                 |
| 400    | Bad Request  | Fix the request parameters                        |
| 401    | Unauthorized | Check your API key                                |
| 403    | Forbidden    | Check permissions / plan tier                     |
| 404    | Not Found    | Verify the resource ID exists                     |
| 429    | Rate Limited | Wait and retry with backoff                       |
| 500    | Server Error | Retry with backoff; contact support if persistent |
