> For the complete Lynkow documentation index in agent-friendly format, see [llms.txt](/llms.txt).

# Error Handling & Resilience

**Publié le** : 2026-11-30
**Catégorie** : Advanced

> **Reference** - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
> 
> - SDK: [Lynkow SDK](/sdk)
> - Types: [SDK Types](/sdk/types)
> - SDK: [`CheckoutService`](/sdk/services/sdk-checkout-service)
> - API: [Storefront API](/storefront-api/overview)

## Prerequisites

- A shared client in `@/lib/lynkow` ([Add Lynkow to an Existing Project](/sdk/getting-started/existing-project))
- A Next.js App Router project

## Catch a LynkowError

Every SDK method rejects with a `LynkowError`. `isLynkowError()` narrows the caught value:

```typescript
import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/lynkow'

try {
  const article = await lynkow.contents.getBySlug('my-article')
} catch (error) {
  if (isLynkowError(error)) {
    console.error(error.code, error.status, error.toJSON())
  }
  throw error
}
```

The fields you branch on:

- `code`: the category of the failure, derived from the HTTP status. Always set.
- `apiCode`: the API's stable reason, taken from the first entry of the error body that carries a code. `undefined` when the body has none, and on network failures.
- `status`: the HTTP status, `0` when no response was received.
- `details`: the entries of the API's error body. Each has a `message`, a `field` on a validation error, and its own `code` when the API sends one.

`toJSON()` returns `name`, `message`, `code`, `apiCode`, `status` and `details` as a plain object for your logs.

## `code` and `apiCode`

`code` tells you what kind of failure happened, `apiCode` tells you why. A checkout refused because the buyer did not accept the terms has `code: 'VALIDATION_ERROR'` and `apiCode: 'TERMS_NOT_ACCEPTED'`. Branch on `code` for generic handling, and on `apiCode` when one status covers several situations the visitor should see differently.

## Error Codes

| `code` | Status | What to do |
| --- | --- | --- |
| `BAD_REQUEST` | 400 | Fix the request, for example a site ID that is not a UUID |
| `UNAUTHORIZED` | 401 | Check the publishable key, or sign the buyer in again |
| `PAYMENT_REQUIRED` | 402 | The site's subscription blocks the operation: hide the feature |
| `FORBIDDEN` | 403 | The request is refused, for example from a domain the site does not allow |
| `NOT_FOUND` | 404 | Render a 404 page |
| `CONFLICT` | 409 | Reload the resource and let the user start again |
| `VALIDATION_ERROR` | 422 | Show `details[].message` next to the matching `field` |
| `TOO_MANY_REQUESTS` | 429 | Rate limited. Reads are retried first, writes are not. When every buyer gets it, see [Server Key and Buyer IP](/sdk/advanced/server-key-buyer-ip) |
| `SERVICE_UNAVAILABLE` | 503 | API temporarily unavailable, after the SDK's retries on reads |
| `INTERNAL_ERROR` | 500 and any other status | Log it and show a generic error |
| `NETWORK_ERROR` | `0` | No response: offline, DNS failure, or a request aborted by its signal |


The `ErrorCode` type also lists `RATE_LIMITED`, `TIMEOUT` and `UNKNOWN`. The SDK's methods never throw them: only the static builders `LynkowError.fromResponse()` and `LynkowError.fromNetworkError()` produce them.

### API error codes (`apiCode`)

The terms and payment refusals of checkout and booking:

```typescript
import { isLynkowError } from 'lynkow'

try {
  await lynkow.checkout.placeOrder({ email: 'buyer@example.com', acceptsTerms: true })
} catch (error) {
  if (isLynkowError(error) && error.apiCode === 'TERMS_PAGE_NOT_CONFIGURED') {
    // The site has no terms page: checkout stays closed until the merchant sets one.
  } else if (isLynkowError(error) && error.apiCode === 'TERMS_NOT_ACCEPTED') {
    // Ask the buyer to tick the terms box.
  } else {
    throw error
  }
}
```

| `apiCode` | `code` | When |
| --- | --- | --- |
| `TERMS_PAGE_NOT_CONFIGURED` | `VALIDATION_ERROR` | `checkout.placeOrder()` or `reservations.book()` while the site has no terms page |
| `TERMS_NOT_ACCEPTED` | `VALIDATION_ERROR` | The same calls without `acceptsTerms: true` |
| `PAYMENT_METHOD_UNAVAILABLE` | `VALIDATION_ERROR` | Card payment is not available for this order. Offline methods still work |
| `PAYMENT_FLOW_UNAVAILABLE` | `VALIDATION_ERROR` | `paymentFlow: 'embedded'` while in-page card payment is not available. No order is created; the hosted payment page still works |
| `PAYMENT_CHECKOUT_UNAVAILABLE` | `SERVICE_UNAVAILABLE` | The card payment page could not start. The order exists unpaid, and a site that tracks stock cancels it |


Both terms refusals point at `acceptsTerms` in `details[0].field`. They create no order or booking and leave the cart open.

Other codes have their own guide: market, shipping, VAT and stock refusals in [Markets, Shipping and VAT](/sdk/features/commerce-markets-shipping-vat), cart errors in [Cart and Checkout](/sdk/features/commerce-cart-checkout). Each endpoint of the [Storefront API reference](/storefront-api/overview) lists the codes it returns.

## Retries and Timeouts

The SDK retries reads (GET requests and text endpoints such as the sitemap) on HTTP 429, HTTP 503 and network errors. It waits with exponential backoff and honors the `Retry-After` header. Writes are sent once. You receive the error only when the retries run out. A sign-in refused for too many failed attempts stays refused for up to 15 minutes: tell the buyer to try again later.

The defaults are `retries: 3`, `backoffMs: 500` and `maxDelayMs: 20000`. Tune them, or turn them off with `retry: false`:

```typescript
// lib/lynkow.ts
import { createClient } from 'lynkow'

export const lynkow = createClient({
  siteId: process.env.NEXT_PUBLIC_LYNKOW_SITE_ID!,
  retry: { retries: 2, maxDelayMs: 5000 },
})
```

The SDK sets no timeout. Pass a signal in the request's `fetchOptions`:

```typescript
const article = await lynkow.contents.getBySlug(slug, {
  fetchOptions: { signal: AbortSignal.timeout(5000) },
})
```

An aborted request throws `NETWORK_ERROR` with status `0` and is not retried.

## Next.js Pages

Map `NOT_FOUND` to `notFound()` and rethrow everything else:

```typescript
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation'
import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/lynkow'

export default async function ArticlePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params

  let article
  try {
    article = await lynkow.contents.getBySlug(slug)
  } catch (error) {
    if (isLynkowError(error) && error.code === 'NOT_FOUND') notFound()
    if (isLynkowError(error)) console.error('[lynkow]', error.toJSON())
    throw error
  }

  return (
    <article>
      <h1>{article.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: article.body }} />
    </article>
  )
}
```

The rethrown error reaches the nearest `error.tsx`. An error thrown in a Server Component arrives there serialized: it is no longer a `LynkowError`, so read `code` and log on the server, before you rethrow.

In a Client Component, the `catch` receives the `LynkowError` itself, so it can show a retry button on `NETWORK_ERROR` or `SERVICE_UNAVAILABLE`:

```typescript
'use client'

import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/lynkow'

async function loadLatest(setError: (message: string | null) => void) {
  try {
    const { data } = await lynkow.contents.list({ limit: 5 })
    setError(null)
    return data
  } catch (error) {
    const transient =
      isLynkowError(error) && (error.code === 'NETWORK_ERROR' || error.code === 'SERVICE_UNAVAILABLE')
    setError(transient ? 'Connection problem. Try again.' : 'Failed to load articles.')
    return []
  }
}
```

On `VALIDATION_ERROR`, each entry of `details` names the `field` it is about. [Dynamic Forms](/sdk/features/forms) maps them to form inputs.

## Next Steps

- [Dynamic Forms](/sdk/features/forms): field errors and spam refusals on submit
- [Cart and Checkout](/sdk/features/commerce-cart-checkout): the errors of a cart and an order
- [Catch-all Routes & Path Resolution](/sdk/advanced/catch-all-routes): 404s and redirects from a path