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

# Error Handling

> The XentFi API uses standard HTTP response codes and a consistent error response format to help you diagnose and resolve issues.

## Error Response Format

All error responses follow this structure:

<ResponseExample>
  ```json theme={null}
  {
      "error": {
          "code": "ERROR_CODE",
          "message": "Human readable description of the error",
          "details": {},
          "timestamp": "2024-01-15T10:30:00.000Z",
          "requestId": "req_123e4567-e89b-12d3-a456-426614174000"
      }
  }
  ```
</ResponseExample>

### Error Fields

| Field       | Type    | Description                         |
| ----------- | ------- | ----------------------------------- |
| `success`   | boolean | Always `false` for errors           |
| `code`      | string  | Machine-readable error code         |
| `message`   | string  | Human-readable error description    |
| `details`   | object  | Additional error context (optional) |
| `timestamp` | string  | ISO 8601 timestamp of the error     |
| `requestId` | string  | Unique identifier for the request   |

## HTTP Status Codes

### 2xx - Success

| Code | Meaning    | Description                         |
| ---- | ---------- | ----------------------------------- |
| 200  | OK         | Request succeeded                   |
| 201  | Created    | Resource created successfully       |
| 204  | No Content | Request succeeded, no response body |

### 4xx - Client Errors

| Code | Meaning              | Description                             |
| ---- | -------------------- | --------------------------------------- |
| 400  | Bad Request          | Invalid request format or parameters    |
| 401  | Unauthorized         | Missing or invalid authentication       |
| 403  | Forbidden            | Valid auth but insufficient permissions |
| 404  | Not Found            | Requested resource doesn't exist        |
| 409  | Conflict             | Resource already exists                 |
| 422  | Unprocessable Entity | Validation failed                       |
| 429  | Too Many Requests    | Rate limit exceeded                     |

### 5xx - Server Errors

| Code | Meaning               | Description                  |
| ---- | --------------------- | ---------------------------- |
| 500  | Internal Server Error | Generic server error         |
| 502  | Bad Gateway           | Upstream service error       |
| 503  | Service Unavailable   | Temporary service disruption |
| 504  | Gateway Timeout       | Upstream timeout             |

## Error Codes

### Authentication Errors

| Code            | HTTP Status | Description                      |
| --------------- | ----------- | -------------------------------- |
| `UNAUTHORIZED`  | 401         | Missing or invalid API key/appId |
| `INVALID_TOKEN` | 401         | Invalid JWT token                |
| `TOKEN_EXPIRED` | 401         | Token has expired                |
| `FORBIDDEN`     | 403         | Insufficient permissions         |

### Validation Errors

| Code               | HTTP Status | Description               |
| ------------------ | ----------- | ------------------------- |
| `VALIDATION_ERROR` | 422         | Request validation failed |
| `BAD_REQUEST`      | 400         | Malformed request         |
| `MISSING_FIELD`    | 422         | Required field missing    |
| `INVALID_FIELD`    | 422         | Field value invalid       |

### Resource Errors

| Code              | HTTP Status | Description             |
| ----------------- | ----------- | ----------------------- |
| `NOT_FOUND`       | 404         | Resource not found      |
| `CONFLICT`        | 409         | Resource already exists |
| `DUPLICATE_ENTRY` | 409         | Duplicate record        |

### Rate Limit Errors

| Code                  | HTTP Status | Description            |
| --------------------- | ----------- | ---------------------- |
| `RATE_LIMIT_EXCEEDED` | 429         | Too many requests      |
| `QUOTA_EXCEEDED`      | 429         | Monthly quota exceeded |

### Payment Errors

| Code                 | HTTP Status | Description               |
| -------------------- | ----------- | ------------------------- |
| `INSUFFICIENT_FUNDS` | 400         | Insufficient balance      |
| `PAYMENT_FAILED`     | 400         | Payment processing failed |
| `PAYMENT_EXPIRED`    | 400         | Payment session expired   |
| `INVALID_NETWORK`    | 400         | Unsupported network       |

### Wallet Errors

| Code                | HTTP Status | Description                 |
| ------------------- | ----------- | --------------------------- |
| `WALLET_NOT_FOUND`  | 404         | Wallet doesn't exist        |
| `INVALID_ADDRESS`   | 400         | Invalid blockchain address  |
| `MONITORING_FAILED` | 400         | Failed to enable monitoring |

## Error Examples

### Validation Error (422)

```json theme={null}
{
    "error": {
        "code": "VALIDATION_ERROR",
        "message": "Request validation failed",
        "details": {
            "fields": [
                {
                    "field": "name",
                    "error": "Name is required"
                },
                {
                    "field": "amount",
                    "error": "Amount must be greater than 0"
                }
            ]
        },
        "timestamp": "2024-01-15T10:30:00.000Z",
        "requestId": "req_123e4567-e89b-12d3-a456-426614174000"
    }
}
```

### Rate Limit Error (429)

```json theme={null}
{
    "error": {
        "code": "RATE_LIMIT_EXCEEDED",
        "message": "Too many requests. Rate limit of 60 requests per minute exceeded.",
        "details": {
            "limit": 60,
            "remaining": 0,
            "resetAt": "2024-01-15T10:31:00.000Z"
        },
        "timestamp": "2024-01-15T10:30:00.000Z",
        "requestId": "req_123e4567-e89b-12d3-a456-426614174000"
    }
}
```

### Authentication Error (401)

```json theme={null}
{
    "error": {
        "code": "UNAUTHORIZED",
        "message": "Invalid API key or appId",
        "timestamp": "2024-01-15T10:30:00.000Z",
        "requestId": "req_123e4567-e89b-12d3-a456-426614174000"
    }
}
```

### Not Found Error (404)

```json theme={null}
{
    "error": {
        "code": "NOT_FOUND",
        "message": "Wallet with id 'wallet_123' not found",
        "timestamp": "2024-01-15T10:30:00.000Z",
        "requestId": "req_123e4567-e89b-12d3-a456-426614174000"
    }
}
```

## Handling Errors by Type

### Validation Errors

```javascript theme={null}
if (error.code === 'VALIDATION_ERROR') {
  // Display field-specific errors to user
  error.details.fields.forEach(field => {
    console.log(`${field.field}: ${field.error}`);
  });
}
```

### Rate Limit Errors

```javascript theme={null}
if (error.code === 'RATE_LIMIT_EXCEEDED') {
  // Wait for reset time
  const resetTime = new Date(error.details.resetAt);
  const waitTime = resetTime - new Date();

  setTimeout(() => {
    retryRequest();
  }, waitTime);
}
```

### Authentication Errors

```javascript theme={null}
if (error.code === 'UNAUTHORIZED') {
  // Refresh credentials or redirect to login
  refreshApiKey();
}
```

## Retry Strategy

### Recommended Retry Logic

```mermaid theme={null}
flowchart TD
    Request[Make Request] --> Response{Response Status}

    Response -->|2xx| Success[Return Success]
    Response -->|429| Rate[Rate Limit]
    Response -->|5xx| Server[Server Error]
    Response -->|4xx| Client[Client Error]

    Rate --> Wait[Wait with Backoff]
    Wait --> Retry{Max Retries?}
    Retry -->|No| Request
    Retry -->|Yes| Fail[Fail]

    Server --> Wait2[Wait with Backoff]
    Wait2 --> Retry2{Max Retries?}
    Retry2 -->|No| Request
    Retry2 -->|Yes| Fail

    Client --> Log[Log Error]
    Log --> Handle[Handle Accordingly]
```

### Exponential Backoff

| Retry | Delay      | Total Wait |
| ----- | ---------- | ---------- |
| 1     | 1 second   | 1 second   |
| 2     | 2 seconds  | 3 seconds  |
| 3     | 4 seconds  | 7 seconds  |
| 4     | 8 seconds  | 15 seconds |
| 5     | 16 seconds | 31 seconds |

### Idempotent Retries

For state-changing operations, use idempotency keys:

```bash theme={null}
curl -X POST https://api.xentfi.com/v1/payment/links \
  -H "Idempotency-Key: unique_key_${RANDOM}" \
  ...
```

## Request ID Tracking

Every error response includes a `requestId`. Use this when contacting support:

```json theme={null}
{
    "error": {
        "requestId": "req_123e4567-e89b-12d3-a456-426614174000"
    }
}
```

## Common Error Scenarios

<AccordionGroup>
  <Accordion title="400 Bad Request - Invalid JSON">
    **Cause:** Malformed JSON in request body.

    **Solution:** Validate JSON syntax before sending.
  </Accordion>

  <Accordion title="401 Unauthorized - Missing headers">
    **Cause:** `apiKey` or `appId` headers missing.

    **Solution:** Include both headers in every request.
  </Accordion>

  <Accordion title="403 Forbidden - Insufficient scope">
    **Cause:** API key lacks required permissions.

    **Solution:** Generate key with appropriate scopes.
  </Accordion>

  <Accordion title="404 Not Found - Wrong endpoint">
    **Cause:** Incorrect URL path.

    **Solution:** Verify endpoint path in documentation.
  </Accordion>

  <Accordion title="409 Conflict - Duplicate resource">
    **Cause:** Resource already exists.

    **Solution:** Use unique identifiers or update existing.
  </Accordion>

  <Accordion title="429 Too Many Requests">
    **Cause:** Rate limit exceeded.

    **Solution:** Implement exponential backoff or upgrade plan.
  </Accordion>
</AccordionGroup>

## Monitoring Errors

### Dashboard

Monitor API errors in the [XentFi Dashboard](https://dashboard.xentfi.com):

* Error rate by endpoint
* Top error codes
* Recent failures
* Request ID lookup

### Webhooks

Configure error alerting via webhooks:

```json theme={null}
{
    "url": "https://yourapp.com/monitoring/errors",
    "events": [
        "api.error"
    ],
    "filters": {
        "statusCodes": [
            400,
            401,
            403,
            404,
            429,
            500
        ]
    }
}
```

## Support

When contacting support, always include:

* The `requestId` from the error response
* Timestamp of the error
* Request details (method, endpoint, body)
* Response headers

**Contact:** [api-support@xentfi.com](mailto:api-support@xentfi.com)

## Related Resources

* [Authentication Guide](/api-reference/authentication) - Fix authentication errors
* [Rate Limits](/getting-started/rate-limits) - Understand rate limiting
* [Idempotency](/api-reference/introduction#idempotency) - Safe request retries
