# Error handling
Source: https://docs.lomi.africa/build/reliability/error-handling

When integrating with lomi., handle API errors so customers get a clear payment outcome and your logs stay useful.

***

title: 'Error handling'
description: "When integrating with lomi., handle API errors so customers get a clear payment outcome and your logs stay useful."
---------------------------------------------------------------------------------------------------------------------------------

This page is integration advice: how to parse API errors in your app. The envelope, status codes, and stable `error.code` list live on [Errors](/api/errors).

lomi. uses conventional HTTP response codes. Use `error.code` for branching, `error.message` for logs, and `request_id` when you contact support.

## Handling common error types

The TypeScript SDK throws `LomiError` subclasses (`LomiValidationError`, `LomiAuthError`, `LomiNotFoundError`, `LomiRateLimitError`). There is no `LomiApiError` class.

### Validation errors (HTTP 400)

These occur when the request data is invalid or missing required fields.

```typescript filename="Handling validation errors"
import { LomiSDK, LomiValidationError, LomiError } from '@lomi./sdk';

const lomi = new LomiSDK({ apiKey: process.env.LOMI_SECRET_KEY! });

try {
  await lomi.checkoutSessions.create({
    amount: -100,
    currency_code: 'INVALID',
  });
} catch (error) {
  if (error instanceof LomiValidationError) {
    console.error('Validation failed:', error.message, error.details);
  } else if (error instanceof LomiError) {
    console.error('API error:', error.statusCode, error.message);
  }
}
```

### Authentication errors (HTTP 401)

These occur when the secret key is missing, invalid, or does not have the necessary permissions.

```typescript filename="Handling authentication errors"
import { LomiSDK, LomiAuthError } from '@lomi./sdk';

const lomi = new LomiSDK({ apiKey: 'invalid-key' });

try {
  await lomi.providers.list();
} catch (error) {
  if (error instanceof LomiAuthError) {
    console.error('Authentication failed:', error.message, error.requestId);
  }
}
```

### Rate limit errors (HTTP 429)

These occur when you exceed the allowed number of requests. Default is 5000 requests per 15 minutes; money-moving writes are 120 per minute. See [Errors](/api/errors#rate-limits).

```typescript filename="Handling rate limit errors"
import { LomiSDK, LomiRateLimitError } from '@lomi./sdk';

const lomi = new LomiSDK({ apiKey: process.env.LOMI_SECRET_KEY! });

try {
  await lomi.providers.list();
} catch (error) {
  if (error instanceof LomiRateLimitError) {
    const details = error.body?.error?.details;
    const retryAfterSeconds =
      details &&
      typeof details === 'object' &&
      !Array.isArray(details) &&
      typeof details.retry_after_seconds === 'number'
        ? details.retry_after_seconds
        : 60;
    console.warn('Rate limit exceeded. Retry after', retryAfterSeconds, 's');
  }
}
```

### Server errors (HTTP 5xx)

These indicate a problem on lomi.'s side. They should be rare. Retry after a delay. A `503` can also mean a muted rail such as `POST /charge/switch`.

## Best practices

1. **Graceful degradation:** show a user-friendly message, not the raw API body. Log `request_id` on your server.
2. **Retry with exponential backoff and jitter** for network errors, `429`, and `5xx`. Do not retry other `4xx` responses until you fix the request. Pair retries with [idempotency keys](/build/reliability/idempotency-keys) on money-moving writes.
3. **Monitor:** track error rates in production and alert on spikes.

```typescript filename="Retries with exponential backoff"
import { LomiError } from '@lomi./sdk';

async function withRetry<T>(
  asyncFn: () => Promise<T>,
  maxRetries = 3,
  initialDelayMs = 1000,
): Promise<T> {
  let attempts = 0;
  while (true) {
    try {
      return await asyncFn();
    } catch (error) {
      attempts++;
      const isRetryable =
        error instanceof LomiError &&
        (error.statusCode === 429 || (error.statusCode ?? 0) >= 500);

      if (!isRetryable || attempts >= maxRetries) {
        throw error;
      }

      const delay = initialDelayMs * Math.pow(2, attempts - 1);
      const jitter = delay * 0.2 * Math.random();
      const waitTime = Math.max(100, delay + jitter);

      await new Promise((resolve) => setTimeout(resolve, waitTime));
    }
  }
}
```

<DocsNextSteps>
  <DocsNextStep href="/build/reliability/idempotency-keys" hint="Safe retries">
    Idempotency keys
  </DocsNextStep>

  <DocsNextStep href="/build/reliability/security-best-practices" hint="Secrets and raw body">
    Security best practices
  </DocsNextStep>

  <DocsNextStep href="/api/errors" hint="Status codes and shapes">
    Error reference
  </DocsNextStep>
</DocsNextSteps>
