ShiwakeDocs

Error Handling

LedgerCoreException and envelope unwrapping.

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

public class LedgerCoreException : Exception
{
    public int StatusCode { get; }
    public string? ApiMessage { get; }
    public string? RawBody { get; }
}
PropertyDescription
StatusCodeHTTP status: use this to switch on what went wrong
ApiMessageThe message field from the ApiResponse envelope
RawBodyFull 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

The standard pattern is an exception filter on StatusCode:

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 for the full status code reference.

Parsing 422 detail payloads

When you need the structured detail from an InsufficientBalanceDetail response:

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

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:

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));

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.

Which statuses are safe to retry?

StatusRetry?Why
400NoYour request is wrong. Retrying won't fix it
401, 403NoCredentials: fix the key, don't retry
404NoThe resource doesn't exist
409NoState conflict: reconcile, don't retry
422NoSemantic failure: the operation is invalid
429YesRate limit; back off and retry with same key
500, 502, 503, 504YesTransient server error; back off and retry

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.

.Handle<LedgerCoreException>(ex => ex.StatusCode == 429 || ex.StatusCode >= 500)
.Handle<HttpRequestException>()
.Handle<TaskCanceledException>()
Edit on GitHub

Last updated on

On this page