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

# Error Handling

> Understanding and handling API errors

The Chariow API uses conventional HTTP response codes to indicate the success or failure of requests.

## Response Format

All API responses follow a consistent format:

```json theme={null}
{
  "message": "Success message or error description",
  "data": {},
  "errors": []
}
```

## HTTP Status Codes

| Code  | Description                                  |
| ----- | -------------------------------------------- |
| `200` | Success - Request completed successfully     |
| `201` | Created - Resource created successfully      |
| `400` | Bad Request - Invalid request parameters     |
| `401` | Unauthorised - Invalid or missing API key    |
| `403` | Forbidden - Access denied to this resource   |
| `404` | Not Found - Resource doesn't exist           |
| `422` | Unprocessable Entity - Validation failed     |
| `429` | Too Many Requests - Rate limit exceeded      |
| `500` | Internal Server Error - Something went wrong |

## Common Errors

### Authentication Errors (401)

```json theme={null}
{
  "message": "Store API key is required",
  "data": [],
  "errors": []
}
```

**Causes:**

* Missing `Authorization` header
* Invalid API key format
* Revoked or expired API key

**Solution:**

```bash theme={null}
# Ensure you include the Authorization header
curl -X GET "https://api.chariow.com/v1/store" \
  -H "Authorization: Bearer sk_live_your_api_key"
```

### Resource Not Found (404)

```json theme={null}
{
  "message": "No query results for model [App\\Models\\Product].",
  "data": [],
  "errors": []
}
```

**Causes:**

* Invalid resource ID
* Resource belongs to a different store
* Resource has been deleted
* Product is not published (for public endpoints)

### Validation Errors (422)

```json theme={null}
{
  "message": "The given data was invalid.",
  "data": [],
  "errors": {
    "email": ["The email field is required."],
    "product_id": ["The selected product_id is invalid."]
  }
}
```

**Causes:**

* Missing required fields
* Invalid field format
* Business rule violations

### Rate Limit Exceeded (429)

```json theme={null}
{
  "message": "Rate limit exceeded. Please retry after 60 seconds.",
  "data": [],
  "errors": []
}
```

**Solution:** Wait for the specified time and retry. See [Rate Limits](/en/resources/rate-limits) for details.

## Handling Errors

### JavaScript Example

```javascript theme={null}
async function makeRequest(endpoint, options = {}) {
  const response = await fetch(`https://api.chariow.com/v1${endpoint}`, {
    ...options,
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
      ...options.headers
    }
  });

  const data = await response.json();

  if (!response.ok) {
    switch (response.status) {
      case 401:
        throw new AuthenticationError(data.message);
      case 404:
        throw new NotFoundError(data.message);
      case 422:
        throw new ValidationError(data.message, data.errors);
      case 429:
        throw new RateLimitError(data.message);
      default:
        throw new ApiError(data.message, response.status);
    }
  }

  return data;
}

// Usage
try {
  const product = await makeRequest('/products/prd_abc123');
  console.log(product);
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log('Product not found');
  } else if (error instanceof ValidationError) {
    console.log('Validation failed:', error.errors);
  } else {
    console.error('API error:', error.message);
  }
}
```

### PHP Example

```php theme={null}
<?php

function makeRequest($endpoint, $method = 'GET', $data = null) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://api.chariow.com/v1{$endpoint}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . getenv('CHARIOW_API_KEY'),
        'Content-Type: application/json'
    ]);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $result = json_decode($response, true);

    if ($httpCode >= 400) {
        throw new Exception($result['message'], $httpCode);
    }

    return $result;
}

// Usage
try {
    $product = makeRequest('/products/prd_abc123');
    print_r($product);
} catch (Exception $e) {
    if ($e->getCode() === 404) {
        echo "Product not found\n";
    } else {
        echo "API error: " . $e->getMessage() . "\n";
    }
}
```

## Error Codes Reference

### Checkout Errors

| Message                 | Cause                             | Solution                          |
| ----------------------- | --------------------------------- | --------------------------------- |
| `Product not found`     | Invalid product ID or unpublished | Use a valid, published product ID |
| `Already purchased`     | Customer owns this product        | Redirect to their purchase        |
| `Product unavailable`   | Out of stock or quantity limit    | Check product availability        |
| `Invalid discount code` | Code doesn't exist or expired     | Verify the discount code          |

### License Errors

| Message                     | Cause                    | Solution                    |
| --------------------------- | ------------------------ | --------------------------- |
| `License not found`         | Invalid license key      | Verify the license key      |
| `License already activated` | Reached activation limit | Show user their activations |
| `License expired`           | Past expiration date     | Prompt for renewal          |
| `License revoked`           | Manually revoked         | Contact support             |

## Best Practices

<AccordionGroup>
  <Accordion title="Always Check Status Codes" icon="check">
    Don't assume success - always check the HTTP status code before processing the response.
  </Accordion>

  <Accordion title="Log Errors" icon="file-lines">
    Log error responses for debugging and monitoring purposes.
  </Accordion>

  <Accordion title="Show User-Friendly Messages" icon="user">
    Translate API errors into user-friendly messages for your customers.
  </Accordion>

  <Accordion title="Implement Retry Logic" icon="rotate">
    For 5xx errors and rate limits, implement automatic retry with exponential backoff.
  </Accordion>
</AccordionGroup>
