# Error Handling

LedgerCoreException and envelope unwrapping.

URL: https://docs.shiwake.app/docs/sdk/error-handling



The SDK unwraps the `ApiResponse` envelope on every call. On success, you
get back the typed `data` payload. On any non-success, the client throws a
`LedgerCoreException` with the status code and parsed message.

LedgerCoreException [#ledgercoreexception]

```csharp
public class LedgerCoreException : Exception
{
    public int StatusCode { get; }
    public string? ApiMessage { get; }
    public string? RawBody { get; }
}
```

| Property     | Description                                                                    |
| ------------ | ------------------------------------------------------------------------------ |
| `StatusCode` | HTTP status: use this to switch on what went wrong                             |
| `ApiMessage` | The `message` field from the `ApiResponse` envelope                            |
| `RawBody`    | Full response body, in case you need to parse a `data` detail payload yourself |

The SDK does not pre-parse 422 detail objects (like `InsufficientBalanceDetail`)
into typed properties. They live in `RawBody` as JSON. This keeps the
exception surface small; if you need the structured detail, deserialize
`RawBody` at the catch site.

Switching on status code [#switching-on-status-code]

The standard pattern is an exception filter on `StatusCode`:

```csharp
try
{
    await ledger.PostJournalEntryAsync(request, idempotencyKey);
}
catch (LedgerCoreException ex) when (ex.StatusCode == 422)
{
    // Business validation failure: probably insufficient balance or unbalanced lines.
    logger.LogWarning("Rejected: {Message}", ex.ApiMessage);
    return Results.UnprocessableEntity(ex.ApiMessage);
}
catch (LedgerCoreException ex) when (ex.StatusCode == 404)
{
    return Results.NotFound(ex.ApiMessage);
}
catch (LedgerCoreException ex) when (ex.StatusCode is 401 or 403)
{
    // Credentials problem: don't retry, page on-call
    logger.LogCritical("Shiwake auth failure: {Message}", ex.ApiMessage);
    throw;
}
```

See [Errors](/docs/api/errors) for the full status code reference.

Parsing 422 detail payloads [#parsing-422-detail-payloads]

When you need the structured detail from an `InsufficientBalanceDetail`
response:

```csharp
catch (LedgerCoreException ex) when (ex.StatusCode == 422)
{
    if (ex.RawBody is not null)
    {
        using var doc = JsonDocument.Parse(ex.RawBody);
        if (doc.RootElement.TryGetProperty("data", out var data)
            && data.ValueKind == JsonValueKind.Object)
        {
            var shortfall = data.GetProperty("shortfall").GetInt64();
            var account   = data.GetProperty("accountCode").GetString();
            logger.LogWarning(
                "Account {Account} short by {Shortfall} pesewas",
                account, shortfall);
        }
    }
    throw;
}
```

Retry policies [#retry-policies]

The SDK never retries automatically. You own the policy. The standard
combination is **Polly** with an exponential-backoff strategy that only
triggers on transient statuses:

```csharp
using Polly;
using Polly.Retry;

var retryPipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions
    {
        ShouldHandle = new PredicateBuilder()
            .Handle<LedgerCoreException>(ex =>
                ex.StatusCode == 429 || ex.StatusCode >= 500),
        BackoffType = DelayBackoffType.Exponential,
        UseJitter   = true,
        Delay       = TimeSpan.FromSeconds(1),
        MaxRetryAttempts = 4
    })
    .Build();

// Always reuse the same idempotency key across retries
var idempotencyKey = Guid.NewGuid().ToString();

var entry = await retryPipeline.ExecuteAsync(
    async ct => await ledger.PostJournalEntryAsync(request, idempotencyKey, ct));
```

<Callout type="warn">
  **Always reuse the original `idempotencyKey` across retries.** Generating
  a fresh key on each attempt defeats the purpose. The engine will treat
  it as a new operation and can post twice. See [Idempotency](/docs/api/idempotency).
</Callout>

Which statuses are safe to retry? [#which-statuses-are-safe-to-retry]

| Status                     | Retry?  | Why                                          |
| -------------------------- | ------- | -------------------------------------------- |
| `400`                      | No      | Your request is wrong. Retrying won't fix it |
| `401`, `403`               | No      | Credentials: fix the key, don't retry        |
| `404`                      | No      | The resource doesn't exist                   |
| `409`                      | No      | State conflict: reconcile, don't retry       |
| `422`                      | No      | Semantic failure: the operation is invalid   |
| `429`                      | **Yes** | Rate limit; back off and retry with same key |
| `500`, `502`, `503`, `504` | **Yes** | Transient server error; back off and retry   |

What about `HttpRequestException`? [#what-about-httprequestexception]

Network failures (DNS, connection reset, timeout) surface as
`HttpRequestException` or `TaskCanceledException`, not `LedgerCoreException`.
Handle them the same way as `5xx`: back off and retry with the same
idempotency key.

```csharp
.Handle<LedgerCoreException>(ex => ex.StatusCode == 429 || ex.StatusCode >= 500)
.Handle<HttpRequestException>()
.Handle<TaskCanceledException>()
```
