# Errors

The ApiResponse envelope, common status codes, and error detail payloads.

URL: https://docs.shiwake.app/docs/api/errors



Every error response uses the same `ApiResponse<T>` envelope as a success
response. Clients can parse both shapes with a single type.

Envelope shape [#envelope-shape]

```json
{
  "code": 422,
  "message": "Debits do not balance credits for currency GHS.",
  "data": null
}
```

<TypeTable
  type="{
  code: { type: &#x22;int&#x22;, required: true, description: &#x22;HTTP status code, always duplicated in the body&#x22; },
  message: { type: &#x22;string&#x22;, required: true, description: &#x22;Human-readable error summary&#x22; },
  data: { type: &#x22;T | null&#x22;, required: true, description: <>For most errors, <code>null</code>. For some (notably <code>422</code>), a structured detail object explaining the failure</> },
}"
/>

<Callout type="info">
  Decide on success by checking `code` is in the 200–299 range. The SDK does
  this for you and throws `LedgerCoreException` on anything else.
</Callout>

Common status codes [#common-status-codes]

| Code  | When                                                                       | Example                                                               |
| ----- | -------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `400` | Malformed request body, missing required headers, invalid query parameters | `Idempotency-Key header is required on all mutating ledger requests.` |
| `401` | Missing or invalid `X-Api-Key` / bearer token                              | `Invalid API key.`                                                    |
| `403` | Credential is valid but tenant is disabled, or policy not satisfied        | `Tenant is disabled.`                                                 |
| `404` | Resource does not exist in the current tenant                              | `Account 'acc_01HZ...' not found.`                                    |
| `409` | Conflict with existing state (duplicate code, already disabled, etc)       | `Account with code 'CLIENT-42' already exists.`                       |
| `422` | Semantically invalid: debits ≠ credits, insufficient balance, etc          | See below                                                             |
| `429` | Rate limit exceeded                                                        | `Too many requests.`                                                  |
| `500` | Unhandled server error                                                     | `An error occured, please try again later.`                           |

422 with detail payloads [#422-with-detail-payloads]

Some `422` responses return a structured detail object in `data` so clients
can react programmatically. The most common is **insufficient balance** when
posting a journal entry:

```json
{
  "code": 422,
  "message": "Insufficient balance on account 'CLIENT-42'.",
  "data": {
    "accountCode": "CLIENT-42",
    "currentBalance": 15000,
    "requestedDebit": 50000,
    "shortfall": 35000
  }
}
```

<TypeTable
  type="{
  accountCode: { type: &#x22;string&#x22;, required: true, description: &#x22;The account that failed the balance check&#x22; },
  currentBalance: { type: &#x22;long&#x22;, required: true, description: &#x22;Current ledger balance in minor units (e.g. pesewas)&#x22; },
  requestedDebit: { type: &#x22;long&#x22;, required: true, description: &#x22;Amount that would have been debited&#x22; },
  shortfall: { type: &#x22;long&#x22;, required: true, description: &#x22;How much more balance is needed to fulfil the debit&#x22; },
}"
/>

Other `422` responses (for example, `Cannot deactivate account 'CLIENT-42': ledger balance is 15000 (minor units).`) return `null` data and rely on the
`message` field.

Validation errors [#validation-errors]

Request body validation (missing required fields, wrong types) is performed
by ASP.NET model binding before the controller runs. These still use the
envelope but may include an expanded `message`:

```json
{
  "code": 400,
  "message": "The Code field is required.",
  "data": null
}
```

Handling errors in code [#handling-errors-in-code]

<CodeBlockTabs defaultValue="csharp">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="csharp">
      C# (SDK)
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="curl">
      curl
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="csharp">
    ```csharp
    try
    {
        var entry = await ledger.PostJournalEntryAsync(request, idempotencyKey);
        logger.LogInformation("Posted {EntryId}", entry.Id);
    }
    catch (LedgerCoreException ex) when (ex.StatusCode == 422)
    {
        // Parse the insufficient-balance detail if you need it
        logger.LogWarning("Posting rejected: {Message}", ex.ApiMessage);
    }
    catch (LedgerCoreException ex) when (ex.StatusCode == 429)
    {
        // Back off and retry with the same Idempotency-Key
        await Task.Delay(TimeSpan.FromSeconds(5));
    }
    catch (LedgerCoreException ex)
    {
        logger.LogError("Shiwake call failed: {Status}: {Message}",
            ex.StatusCode, ex.ApiMessage);
        throw;
    }
    ```
  </CodeBlockTab>

  <CodeBlockTab value="curl">
    ```bash
    response=$(curl -sS -w "\n%{http_code}" -X POST "$URL" \
      -H "X-Api-Key: $KEY" \
      -H "Idempotency-Key: $(uuidgen)" \
      -H "Content-Type: application/json" \
      -d "$BODY")

    status=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [ "$status" -ge 400 ]; then
      echo "Error $status: $(echo "$body" | jq -r '.message')"
      exit 1
    fi
    ```
  </CodeBlockTab>
</CodeBlockTabs>

Retry guidance [#retry-guidance]

| Status                     | Retry? | How                                                     |
| -------------------------- | ------ | ------------------------------------------------------- |
| `400`                      | No     | Fix the request                                         |
| `401`, `403`               | No     | Rotate credentials or re-authenticate                   |
| `404`                      | No     | The resource does not exist                             |
| `409`                      | No     | Reconcile with existing state                           |
| `422`                      | No     | The operation is semantically invalid                   |
| `429`                      | Yes    | Exponential backoff with jitter, same `Idempotency-Key` |
| `500`, `502`, `503`, `504` | Yes    | Exponential backoff with jitter, same `Idempotency-Key` |

<Callout type="warn">
  Always reuse the original `Idempotency-Key` on retries. A fresh key on a
  retry is a new logical operation and may cause duplicate posts.
</Callout>
