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

# Handling errors

> How errors look, which to retry, and a client that handles them.

There are two kinds of failure:

1. **The request is refused.** You get a `4xx` or `5xx` with an error envelope, and nothing happened. See the [error reference](https://docs.cloudpay.africa/errors/reference.md).
2. **The payment fails later.** The request was accepted with `202`, but the rail declined the payment. The payment ends with `status: failed` and a `failure_reason`. See [Payment failures](https://docs.cloudpay.africa/errors/payment-failures.md).

## The error envelope

```json theme={null}
{
  "status": { "ok": false, "code": 422, "desc": "Unprocessable Entity" },
  "errors": {
    "code": "insufficient_funds",
    "message": "the main account does not hold the amount plus the fee"
  }
}
```

| Field | Use it for |
| - | - |
| `errors.code` | **Your logic.** It's stable, snake\_case and never reworded. |
| `errors.message` | Logs, and messages to your staff. It's written in plain English and may change. |
| `status.code` | The same as the HTTP status. |

> [!WARNING]
>
> Don't parse `message`, and don't show it to your customers as is. Map the codes you expect to your own wording, and give everything else a generic message.

## What each status means

| HTTP | Meaning | Retry? |
| - | - | - |
| `400` | The request is malformed: a missing field, a bad format or an unknown field | No. Fix the request. |
| `401` | No credentials, wrong credentials, or the session ended | No. Fix the key or sign in again. |
| `403` | Authenticated but not allowed: a scope, environment, approval or limit | No. It needs an action from you or Cloudpay. |
| `404` | Doesn't exist, or isn't yours (Cloudpay doesn't say which) | No |
| `409` | Conflicts with the current state: a reused key, or the wrong status for this action | No. Re-read the resource first. |
| `422` | Well formed, but against a business rule: funds, limits, KYB | No, not until the situation changes |
| `423` | Locked after too many failed attempts | Yes, after the lock ends |
| `429` | Too many requests of this kind | Yes, after a few minutes |
| `500` | Cloudpay failed. The response carries `internal`, and the cause is logged on our side. | Yes, with the same idempotency key |
| `502` / `503` | A provider or dependency is down | Yes, with backoff |

Money requests are always safe to retry **with the same `idempotency_key`**. See [Idempotency](https://docs.cloudpay.africa/concepts/idempotency.md).

## A client that handles errors

```ts TypeScript theme={null}
class CloudpayError extends Error {
  constructor(public status: number, public code: string, message: string) {
    super(message);
  }
  get retryable() {
    return this.status === 429 || this.status >= 500;
  }
}

async function cloudpay<T>(path: string, init: RequestInit = {}, attempt = 0): Promise<T> {
  let res: Response;
  try {
    res = await fetch(`https://api.cloudpay.africa/cloudpay${path}`, {
      ...init,
      headers: {
        Authorization: `Bearer ${process.env.CLOUDPAY_KEY}`,
        "Content-Type": "application/json",
        ...init.headers,
      },
    });
  } catch (e) {
    // network error: retrying with the same body (and idempotency_key) is safe
    if (attempt < 3) return retry();
    throw e;
  }
  const body = await res.json();
  if (body.status.ok) return body.data as T;

  const err = new CloudpayError(res.status, body.errors.code, body.errors.message);
  if (err.retryable && attempt < 3) return retry();
  throw err;

  async function retry() {
    await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
    return cloudpay<T>(path, init, attempt + 1);
  }
}

// usage
try {
  await cloudpay(`/v1/merchants/${MID}/disbursements`, {
    method: "POST",
    body: JSON.stringify({ msisdn, amount, idempotency_key: `payout-${invoice.id}` }),
  });
} catch (e) {
  if (e instanceof CloudpayError) {
    switch (e.code) {
      case "insufficient_funds": return notifyFinance("Top up the Cloudpay balance");
      case "payee_unsupported":  return askForAnotherPayoutMethod();
      case "live_mode_required": throw new Error("CLOUDPAY_KEY is a test key in production");
    }
  }
  throw e;
}
```

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

class CloudpayError(Exception):
    def __init__(self, status, code, message):
        super().__init__(message)
        self.status, self.code = status, code

def cloudpay(method, path, json=None, attempt=0):
    try:
        r = requests.request(method, f"https://api.cloudpay.africa/cloudpay{path}", json=json, timeout=30,
                             headers={"Authorization": f"Bearer {CLOUDPAY_KEY}"})
    except requests.RequestException:
        if attempt < 3:
            time.sleep(2 ** attempt)
            return cloudpay(method, path, json, attempt + 1)
        raise
    body = r.json()
    if body["status"]["ok"]:
        return body["data"]
    if (r.status_code == 429 or r.status_code >= 500) and attempt < 3:
        time.sleep(2 ** attempt)
        return cloudpay(method, path, json, attempt + 1)
    raise CloudpayError(r.status_code, body["errors"]["code"], body["errors"]["message"])
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.