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

# Error Handling

> Understand error codes and how to handle errors gracefully.

## Response Format

All agntdata API responses follow a consistent format. Successful responses:

```json theme={null}
{
  "success": true,
  "data": {
    // Response data
  },
  "meta": {
    "costCents": 1,
    "purchasedBalanceCents": 950,
    "subscriptionRemainingCents": 0,
    "cached": false,
    "latencyMs": 245
  }
}
```

Error responses:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error description",
    "retryAfter": 30
  }
}
```

## HTTP Status Codes

| Status | Meaning                                        |
| ------ | ---------------------------------------------- |
| `200`  | Success                                        |
| `400`  | Bad Request — Invalid parameters               |
| `401`  | Unauthorized — Invalid or missing API key      |
| `404`  | Not Found — Resource or endpoint doesn't exist |
| `429`  | Too Many Requests — Rate limit exceeded        |
| `500`  | Internal Server Error — Something went wrong   |

## Error Codes

### Authentication Errors

| Code                   | Description                | Solution                      |
| ---------------------- | -------------------------- | ----------------------------- |
| `UNAUTHORIZED`         | Invalid or missing API key | Check your API key is correct |
| `INSUFFICIENT_CREDITS` | Not enough credits         | Top up your credit balance    |

### Request Errors

| Code                 | Description                           | Solution                                    |
| -------------------- | ------------------------------------- | ------------------------------------------- |
| `VALIDATION_ERROR`   | Required parameter missing or invalid | Check the API reference for required params |
| `ENDPOINT_NOT_FOUND` | Endpoint doesn't exist                | Verify the endpoint path                    |
| `PROVIDER_NOT_FOUND` | Platform not available                | Check available platforms                   |

### Rate Limit Errors

| Code           | Description       | Solution                    |
| -------------- | ----------------- | --------------------------- |
| `RATE_LIMITED` | Too many requests | Wait and retry with backoff |

### Data Errors

| Code                   | Description                      | Solution                          |
| ---------------------- | -------------------------------- | --------------------------------- |
| `NOT_FOUND`            | Resource doesn't exist           | Verify the username/ID is correct |
| `PROVIDER_ERROR`       | Upstream platform error          | Retry later                       |
| `PROVIDER_UNAVAILABLE` | Platform temporarily unavailable | Retry later                       |

### Server Errors

| Code             | Description             | Solution                             |
| ---------------- | ----------------------- | ------------------------------------ |
| `INTERNAL_ERROR` | Unexpected server error | Retry, contact support if persistent |
| `CONFLICT`       | Resource conflict       | Check for duplicate resources        |

## Handling Errors

### JavaScript/TypeScript

```typescript theme={null}
async function fetchProfile(username: string) {
  const response = await fetch(
    `https://api.agntdata.dev/v1/data/linkedin/get-profile?username=${username}`,
    {
      headers: {
        'Authorization': `Bearer ${process.env.AGNTDATA_API_KEY}`
      }
    }
  );

  const data = await response.json();

  if (!data.success) {
    switch (data.error.code) {
      case 'NOT_FOUND':
        throw new Error(`Profile not found: ${username}`);
      case 'RATE_LIMITED':
        const retryAfter = data.error.retryAfter || 30;
        await sleep(retryAfter * 1000);
        return fetchProfile(username);
      case 'INSUFFICIENT_CREDITS':
        throw new Error('Please top up your credits');
      default:
        throw new Error(data.error.message);
    }
  }

  return data.data;
}
```

### Python

With raw HTTP, branch on `error.code` and retry or surface user actions for
the cases you want to handle:

```python theme={null}
import os
import time

import httpx

API_KEY = os.environ["AGNTDATA_API_KEY"]

def fetch_profile(username: str) -> dict:
    response = httpx.get(
        "https://api.agntdata.dev/v1/data/linkedin/get-profile",
        params={"username": username},
        headers={"Authorization": f"Bearer {API_KEY}"},
    )
    data = response.json()
    if data["success"]:
        return data["data"]

    code = data["error"]["code"]
    if code == "NOT_FOUND":
        raise ValueError(f"Profile not found: {username}")
    if code == "RATE_LIMITED":
        time.sleep(data["error"].get("retryAfter", 30))
        return fetch_profile(username)
    if code == "INSUFFICIENT_CREDITS":
        raise Exception("Please top up your credits")
    raise RuntimeError(data["error"]["message"])
```

## Retry Strategy

For transient errors, implement exponential backoff:

```javascript theme={null}
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      const data = await response.json();
      
      if (data.success) {
        return data;
      }
      
      // Don't retry client errors (4xx except 429)
      if (response.status >= 400 && response.status < 500 && response.status !== 429) {
        throw new Error(data.error.message);
      }
      
      // Retry with backoff for rate limits and server errors
      const delay = Math.pow(2, attempt) * 1000;
      await sleep(delay);
      
    } catch (error) {
      if (attempt === maxRetries - 1) throw error;
    }
  }
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Rate Limits" icon="gauge" href="/concepts/rate-limits">
    Understand rate limits and how to stay within them.
  </Card>

  <Card title="API Reference" icon="code" href="/apis/overview">
    Browse endpoint documentation.
  </Card>
</CardGroup>
