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

# Error handling

> Handle SDK and microservice errors in partner applications

The Lomadee SDK does not wrap failures in a custom error taxonomy. When a request fails, the underlying **Axios** error propagates to your `await`—your application decides how to log, retry, and present the failure.

## What can go wrong

The table below describes **typical upstream HTTP behavior** you may encounter. Status codes and error bodies are **not normalized by the SDK** and can vary by microservice—do not treat this as a guaranteed taxonomy.

| Situation                      | Typical signal                                   | Suggested response                                                       |
| ------------------------------ | ------------------------------------------------ | ------------------------------------------------------------------------ |
| Invalid or revoked `authKey`   | HTTP **401** / **403** from the upstream service | Fail fast; alert ops; do not retry until the key is fixed                |
| Missing resource               | HTTP **404**                                     | Treat as a domain condition (not found), not a transport error           |
| Validation rejected by service | HTTP **400** / **422**                           | Fix the payload; retry only after correcting input                       |
| Upstream unavailable           | HTTP **502** / **503** / **504**                 | Optional limited retry for **idempotent reads**; see below               |
| Network / DNS issues           | Axios error without `response`                   | Log and retry cautiously for reads; avoid blind retries on writes        |
| Request exceeded SDK timeout   | Axios timeout (**10s** fixed per client)         | Treat like a transient failure for reads; investigate latency for writes |

The SDK sets a **10 second timeout** on the shared HTTP client. There is no built-in retry or circuit breaker—you implement resilience in your application layer if needed.

## Basic handling pattern

Start with explicit `try/catch` around SDK calls. Log enough context for debugging (resource, method, correlation id) but **never** log headers or the `authKey`:

```typescript theme={null}
import { Lomadee } from '@thelomadee/sdk';

const sdk = new Lomadee({
  authKey: process.env.LOMADEE_AUTH_KEY!,
});

async function fetchLatestTerms() {
  try {
    return await sdk.terms.latest();
  } catch (error) {
    // Narrow safely without assuming Axios-specific helpers
    if (error && typeof error === 'object' && 'response' in error) {
      const status = (error as { response?: { status?: number } }).response?.status;
      console.error('Terms request failed', { status });
    } else {
      console.error('Terms request failed', {
        message: error instanceof Error ? error.message : 'Unknown error',
      });
    }
    throw error; // or map to your application's error type
  }
}
```

<Note>
  If you prefer Axios utilities such as `isAxiosError`, import them from the **`axios`** package in your application. The SDK lists Axios as its own dependency; applications that import Axios directly should declare **`axios`** as a direct dependency to avoid relying on transitive installs.
</Note>

## Map HTTP status to application behavior

Design handlers around **intent**, not around SDK internals:

```typescript theme={null}
function isRetryableReadError(error: unknown): boolean {
  if (!error || typeof error !== 'object' || !('response' in error)) {
    // No response usually means network/timeout — reads may retry
    return true;
  }
  const status = (error as { response?: { status?: number } }).response?.status;
  return status === 502 || status === 503 || status === 504;
}
```

Use status-aware branching in your API layer to return appropriate HTTP codes and messages to **your** callers. The SDK does not translate upstream bodies into a stable public error schema.

## Retries and timeouts

Because the SDK does not retry automatically, you may add retries in application code. Apply these guardrails:

<Warning>
  **Do not retry write operations indiscriminately.** Methods such as `transactions.create`, `commissions.create`, and `affiliates.create` may have side effects. Retrying without an idempotency strategy can duplicate data. Prefer retries for **read** calls (`get`, `list`, `latest`) when upstream returns a transient 5xx or a timeout.
</Warning>

Guidelines:

* **Reads** (`list`, `get`, `latest`): up to a small number of retries with exponential backoff when you see 502/503/504 or a timeout
* **Creates / updates / deletes**: fail visibly on the first error unless your integration design explicitly supports safe replay (confirm with Lomadee before implementing)
* **Auth errors (401/403)**: never retry—fix configuration
* **Client errors (4xx)**: fix input; do not retry the same payload

Example: bounded retry for a read-only terms check:

```typescript theme={null}
import { Lomadee } from '@thelomadee/sdk';

async function latestTermsWithRetry(sdk: Lomadee, maxAttempts = 3) {
  let lastError: unknown;

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await sdk.terms.latest();
    } catch (error) {
      lastError = error;
      if (!isRetryableReadError(error) || attempt === maxAttempts) {
        throw error;
      }
      await new Promise((r) => setTimeout(r, attempt * 200));
    }
  }

  throw lastError;
}
```

## Observability without leaking secrets

* Log **HTTP status**, the **SDK method name** (for example `terms.latest`), and your own trace ids
* Avoid logging full Axios `config.headers`—they contain `x-auth-key`
* Return generic messages to end users; keep detailed upstream bodies in server-side logs only

## When errors persist

1. Verify `LOMADEE_AUTH_KEY` and `environment` match what Lomadee provisioned ([Environments and secrets](/docs/sdk/guides/environments-and-secrets))
2. Re-run the [Quickstart](/docs/sdk/quickstart) `sdk.terms.latest()` check in the same environment
3. Contact Lomadee support with timestamps, environment, and the resource method—**not** your raw `authKey`

## Related documentation

* [How the SDK works](/docs/sdk/concepts/how-the-sdk-works) — timeout, shared client, no built-in retry
* [Client reference](/docs/sdk/reference/client) — constructor and configuration types
