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

# Error Handling

> Understanding and handling CashQ API errors

## Error Response Structure

When an API request fails, the response will have `success` set to `"false"` (string) and include an `error` object with details.

### Error Object

<ResponseField name="error" type="object">
  Contains error information

  <Expandable title="Properties">
    <ResponseField name="message" type="string">
      Human-readable error description explaining what went wrong
    </ResponseField>

    <ResponseField name="code" type="string">
      Machine-readable error code for programmatic handling
    </ResponseField>
  </Expandable>
</ResponseField>

### Example Error Response

```json theme={null}
{
  "error": {
    "message": "An error occurred while we were processing your request",
    "code": "internal_server_error"
  },
  "success": "false"
}
```

## Common Error Codes

### Authentication Errors

<AccordionGroup>
  <Accordion title="authentication_error">
    **Cause:** Invalid or missing API key

    **Solution:**

    * Verify your API key is correct
    * Ensure the `API-KEY` header is included in the request
    * Check you're using the right key for the environment (sandbox vs production)

    ```json theme={null}
    {
      "error": {
        "message": "Invalid or missing API key",
        "code": "authentication_error"
      },
      "success": "false"
    }
    ```
  </Accordion>
</AccordionGroup>

### Transaction Errors

<AccordionGroup>
  <Accordion title="insufficient_funds">
    **Cause:** Merchant account doesn't have enough balance for the transaction

    **Solution:**

    * Check your balance using the `/api/agent_balance` endpoint
    * Add funds to your merchant account
    * Reduce the transfer amount

    ```json theme={null}
    {
      "error": {
        "message": "Insufficient funds in merchant account",
        "code": "insufficient_funds"
      },
      "success": "false"
    }
    ```
  </Accordion>

  <Accordion title="invalid_phone_number">
    **Cause:** Phone number format is incorrect

    **Solution:**

    * Use E.164 format without the `+` sign
    * Format: `[country code][subscriber number]`
    * Example: `16175551212` for a US number

    ```json theme={null}
    {
      "error": {
        "message": "Invalid phone number format",
        "code": "invalid_phone_number"
      },
      "success": "false"
    }
    ```
  </Accordion>

  <Accordion title="transfer_not_found">
    **Cause:** The specified transfer ID doesn't exist

    **Solution:**

    * Verify the transfer ID is correct
    * Check if the transfer was created in the same environment
    * Ensure you're using the ID returned from the transfer creation

    ```json theme={null}
    {
      "error": {
        "message": "Transfer not found",
        "code": "transfer_not_found"
      },
      "success": "false"
    }
    ```
  </Accordion>

  <Accordion title="kyc_not_verified">
    **Cause:** Recipient account is not KYC verified and cannot receive the transfer amount

    **Solution:**

    * Check KYC status using `/api/kyc/:account` endpoint
    * Direct user to complete KYC verification via the `kyc_url` provided
    * Reduce transfer amount to within the unverified limit

    ```json theme={null}
    {
      "error": {
        "message": "Recipient KYC verification required",
        "code": "kyc_not_verified"
      },
      "success": "false"
    }
    ```
  </Accordion>
</AccordionGroup>

### Server Errors

<AccordionGroup>
  <Accordion title="internal_server_error">
    **Cause:** An unexpected error occurred on the server

    **Solution:**

    * Retry the request after a brief delay
    * If the error persists, contact support
    * Check the CashQ status page for any ongoing issues

    ```json theme={null}
    {
      "error": {
        "message": "An error occurred while we were processing your request",
        "code": "internal_server_error"
      },
      "success": "false"
    }
    ```
  </Accordion>

  <Accordion title="service_unavailable">
    **Cause:** The API service is temporarily unavailable

    **Solution:**

    * Implement retry logic with exponential backoff
    * Wait and retry the request
    * Contact support if the issue persists
  </Accordion>
</AccordionGroup>

### Validation Errors

<AccordionGroup>
  <Accordion title="invalid_request">
    **Cause:** Request parameters are missing or invalid

    **Solution:**

    * Review the endpoint documentation
    * Verify all required parameters are included
    * Check parameter types and formats
    * Ensure JSON is properly formatted

    ```json theme={null}
    {
      "error": {
        "message": "Invalid request parameters",
        "code": "invalid_request"
      },
      "success": "false"
    }
    ```
  </Accordion>

  <Accordion title="invalid_amount">
    **Cause:** Transfer amount is invalid (negative, zero, or exceeds limits)

    **Solution:**

    * Ensure amount is a positive number
    * Check minimum and maximum transfer limits
    * Verify amount format (string with decimal)
  </Accordion>
</AccordionGroup>

## Error Handling Best Practices

### 1. Always Check Success Field

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

if (data.success !== true && data.success !== 'true') {
  // Handle error
  handleError(data.error);
} else {
  // Process successful response
  processData(data);
}
```

### 2. Implement Retry Logic

For transient errors like `internal_server_error`, implement retry with exponential backoff:

<CodeGroup>
  ```javascript Node.js theme={null}
  async function makeRequestWithRetry(url, options, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
      try {
        const response = await fetch(url, options);
        const data = await response.json();
        
        if (data.success === true || data.success === 'true') {
          return data;
        }
        
        // Don't retry for client errors
        if (data.error.code === 'authentication_error' || 
            data.error.code === 'invalid_request') {
          throw new Error(data.error.message);
        }
        
        // Retry for server errors
        if (i < maxRetries - 1) {
          await new Promise(resolve => 
            setTimeout(resolve, Math.pow(2, i) * 1000)
          );
        }
      } catch (error) {
        if (i === maxRetries - 1) throw error;
      }
    }
  }
  ```

  ```python Python theme={null}
  import time
  import requests

  def make_request_with_retry(url, headers, max_retries=3):
      for i in range(max_retries):
          try:
              response = requests.get(url, headers=headers)
              data = response.json()
              
              if data.get('success') in [True, 'true']:
                  return data
              
              # Don't retry for client errors
              if data['error']['code'] in ['authentication_error', 'invalid_request']:
                  raise Exception(data['error']['message'])
              
              # Retry for server errors
              if i < max_retries - 1:
                  time.sleep(2 ** i)
          except Exception as e:
              if i == max_retries - 1:
                  raise e
  ```
</CodeGroup>

### 3. Use Error Codes for Logic

```javascript theme={null}
function handleError(error) {
  switch (error.code) {
    case 'authentication_error':
      // Redirect to login or refresh credentials
      redirectToLogin();
      break;
      
    case 'insufficient_funds':
      // Show balance warning to user
      showInsufficientFundsWarning();
      break;
      
    case 'kyc_not_verified':
      // Direct user to KYC verification
      redirectToKYC(error.kyc_url);
      break;
      
    case 'internal_server_error':
      // Retry the request
      retryRequest();
      break;
      
    default:
      // Show generic error message
      showErrorMessage(error.message);
  }
}
```

### 4. Log Errors for Debugging

```javascript theme={null}
function logError(endpoint, error, requestData) {
  console.error('API Error:', {
    timestamp: new Date().toISOString(),
    endpoint: endpoint,
    errorCode: error.code,
    errorMessage: error.message,
    requestData: requestData
  });
  
  // Send to your logging service
  sendToLoggingService({
    level: 'error',
    endpoint: endpoint,
    error: error,
    request: requestData
  });
}
```

### 5. Provide User-Friendly Messages

Don't show raw error messages to users. Translate error codes into user-friendly messages:

```javascript theme={null}
const userFriendlyMessages = {
  'authentication_error': 'Unable to authenticate. Please check your credentials.',
  'insufficient_funds': 'Insufficient balance. Please add funds to your account.',
  'invalid_phone_number': 'Please enter a valid phone number.',
  'kyc_not_verified': 'Recipient needs to complete verification to receive this amount.',
  'internal_server_error': 'Something went wrong. Please try again.',
  'transfer_not_found': 'Transfer not found. Please check the transfer ID.'
};

function getUserMessage(errorCode) {
  return userFriendlyMessages[errorCode] || 'An error occurred. Please try again.';
}
```

## HTTP Status Codes

In addition to the error object in the response body, check HTTP status codes:

| Status Code | Meaning               | Action                                 |
| ----------- | --------------------- | -------------------------------------- |
| 200         | OK                    | Check `success` field in response body |
| 400         | Bad Request           | Fix request parameters                 |
| 401         | Unauthorized          | Check API key                          |
| 404         | Not Found             | Verify endpoint URL                    |
| 429         | Too Many Requests     | Implement rate limiting                |
| 500         | Internal Server Error | Retry with backoff                     |
| 503         | Service Unavailable   | Retry later                            |

## Error Handling Checklist

Before deploying to production, ensure you have:

* [ ] Checked the `success` field in all API responses
* [ ] Implemented retry logic for transient errors
* [ ] Used error codes for programmatic handling
* [ ] Logged errors for debugging and monitoring
* [ ] Provided user-friendly error messages
* [ ] Handled authentication errors appropriately
* [ ] Tested error scenarios in sandbox
* [ ] Set up monitoring and alerting for errors

## Need Help?

<Card title="Contact Support" icon="envelope" href="mailto:support@mycashq.com" horizontal>
  Encountering persistent errors? Our support team is here to help.
</Card>
