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

# Error Handling

> Learn how to handle API errors gracefully

## Response Format

All Xenia API responses follow a consistent format:

### Success Response

```json theme={null}
{
  "status": true,
  "statusCode": 200,
  "message": "Success",
  "data": { ... },
  "requestId": "req_abc123"
}
```

### Error Response

```json theme={null}
{
  "status": false,
  "statusCode": 400,
  "message": "Error description",
  "error": {
    "code": "VALIDATION_ERROR",
    "details": [ ... ]
  },
  "requestId": "req_abc123"
}
```

<Tip>
  The `requestId` is useful for debugging. Include it when contacting support.
</Tip>

***

## HTTP Status Codes

| Code  | Status                | Description                       |
| ----- | --------------------- | --------------------------------- |
| `200` | OK                    | Request successful                |
| `201` | Created               | Resource created successfully     |
| `400` | Bad Request           | Invalid request parameters        |
| `401` | Unauthorized          | Missing or invalid authentication |
| `403` | Forbidden             | Insufficient permissions          |
| `404` | Not Found             | Resource does not exist           |
| `409` | Conflict              | Resource already exists           |
| `422` | Unprocessable Entity  | Validation failed                 |
| `429` | Too Many Requests     | Rate limit exceeded               |
| `500` | Internal Server Error | Server-side error                 |

***

## Common Errors & Solutions

### 401 Unauthorized

**Error:**

```json theme={null}
{
  "status": false,
  "statusCode": 401,
  "message": "Unauthorized - Missing or invalid authentication."
}
```

**Causes:**

* Missing `x-client-key` or `x-client-secret` headers
* Invalid or expired credentials
* API access not enabled for workspace

**Solutions:**

1. Verify your API credentials are correct
2. Check that credentials haven't been revoked
3. Ensure `workspace-id` header is included
4. Confirm API access is enabled for your workspace

```bash theme={null}
# Correct authentication
curl -X GET "https://api.xenia.team/api/v1/mgt/users" \
  -H "x-client-key: YOUR_CLIENT_KEY" \
  -H "x-client-secret: YOUR_CLIENT_SECRET" \
  -H "workspace-id: YOUR_WORKSPACE_ID"
```

***

### 403 Forbidden

**Error:**

```json theme={null}
{
  "status": false,
  "statusCode": 403,
  "message": "Forbidden - Insufficient permissions."
}
```

**Causes:**

* API user lacks required permission
* Resource is not accessible to this user
* Feature not enabled for workspace

**Solutions:**

1. Check the API user's role and permissions
2. Verify the resource belongs to your workspace
3. Contact admin to grant necessary permissions

***

### 404 Not Found

**Error:**

```json theme={null}
{
  "status": false,
  "statusCode": 404,
  "message": "Not Found - Resource does not exist."
}
```

**Causes:**

* Invalid resource ID (UUID)
* Resource has been deleted
* Resource belongs to a different workspace

**Solutions:**

1. Verify the resource ID is correct
2. Check that the resource still exists
3. Ensure you're using the correct workspace

***

### 400 Bad Request

**Error:**

```json theme={null}
{
  "status": false,
  "statusCode": 400,
  "message": "Bad Request - Invalid parameters.",
  "error": {
    "details": [
      {
        "field": "emailId",
        "message": "Invalid email format"
      }
    ]
  }
}
```

**Causes:**

* Missing required fields
* Invalid field format (e.g., invalid UUID, email)
* Invalid JSON syntax

**Solutions:**

1. Review the API documentation for required fields
2. Validate data formats before sending
3. Check JSON syntax is valid

***

### 422 Unprocessable Entity

**Error:**

```json theme={null}
{
  "status": false,
  "statusCode": 422,
  "message": "Validation failed",
  "error": {
    "details": [
      {
        "field": "dueDate",
        "message": "Due date must be in the future"
      }
    ]
  }
}
```

**Causes:**

* Business logic validation failed
* Invalid relationships between fields
* Constraint violations

**Solutions:**

1. Review validation error details
2. Ensure data meets business rules
3. Check relationships between fields

***

### 429 Too Many Requests

**Error:**

```json theme={null}
{
  "status": false,
  "statusCode": 429,
  "message": "Rate limit exceeded. Please try again later.",
  "error": {
    "retryAfter": 60
  }
}
```

**Causes:**

* Too many requests in a short period
* Exceeding API rate limits

**Solutions:**

1. Implement exponential backoff
2. Cache responses where possible
3. Batch operations when available

```javascript theme={null}
// Exponential backoff example
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    const response = await fetch(url, options);

    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After') || 60;
      await new Promise(r => setTimeout(r, retryAfter * 1000));
      continue;
    }

    return response;
  }
  throw new Error('Max retries exceeded');
}
```

***

### 500 Internal Server Error

**Error:**

```json theme={null}
{
  "status": false,
  "statusCode": 500,
  "message": "Internal Server Error",
  "requestId": "req_abc123"
}
```

**Causes:**

* Server-side issue
* Unexpected error condition

**Solutions:**

1. Retry the request after a brief delay
2. If persistent, contact support with the `requestId`

***

## Best Practices

### 1. Always Check Status

```javascript theme={null}
const response = await fetch(url, options);
const data = await response.json();

if (!data.status) {
  // Handle error
  console.error(`Error ${data.statusCode}: ${data.message}`);
  return;
}

// Process successful response
const result = data.data;
```

### 2. Validate UUIDs

Before making requests, validate that IDs are valid UUIDs:

```javascript theme={null}
function isValidUUID(id) {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
  return uuidRegex.test(id);
}

if (!isValidUUID(userId)) {
  throw new Error('Invalid user ID format');
}
```

### 3. Handle Network Errors

```javascript theme={null}
try {
  const response = await fetch(url, options);
  const data = await response.json();
  // Process response
} catch (error) {
  if (error.name === 'TypeError') {
    // Network error
    console.error('Network error - check your connection');
  } else {
    // Other error
    console.error('Unexpected error:', error);
  }
}
```

### 4. Log Request IDs

Always log the `requestId` from responses for debugging:

```javascript theme={null}
const data = await response.json();
console.log(`Request ID: ${data.requestId}`);

if (!data.status) {
  // Include requestId in error logs
  console.error(`Error [${data.requestId}]: ${data.message}`);
}
```

***

## Debugging Tips

<AccordionGroup>
  <Accordion title="Check request headers">
    Ensure all required headers are present:

    * `x-client-key`
    * `x-client-secret`
    * `workspace-id`
    * `Content-Type: application/json`
  </Accordion>

  <Accordion title="Verify JSON payload">
    Use a JSON validator to ensure your request body is valid JSON.
    Common issues:

    * Trailing commas
    * Unquoted strings
    * Invalid escape characters
  </Accordion>

  <Accordion title="Test with cURL first">
    Before implementing in code, test requests with cURL to isolate issues:

    ```bash theme={null}
    curl -v -X GET "https://api.xenia.team/api/v1/mgt/users" \
      -H "x-client-key: YOUR_KEY" \
      -H "x-client-secret: YOUR_SECRET" \
      -H "workspace-id: YOUR_WORKSPACE"
    ```
  </Accordion>

  <Accordion title="Check API status">
    If experiencing widespread issues, check Xenia's system status or contact support.
  </Accordion>
</AccordionGroup>

***

## Getting Help

If you encounter persistent errors:

1. **Gather Information:**
   * Request ID (`requestId`)
   * Full error message
   * Request endpoint and method
   * Request payload (without sensitive data)

2. **Contact Support:**
   * Email: [support@xenia.team](mailto:support@xenia.team)
   * Include all gathered information

***

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api-reference/endpoints/authentication/index">
    Explore the complete API reference
  </Card>

  <Card title="Users API" icon="users" href="/api-reference/endpoints/users/get-users">
    Start managing users
  </Card>
</CardGroup>
