# Error handling (https://eulabel.eu/docs/knowledge-base/guides/error-handling)

> Fetch the complete documentation index at: https://eulabel.eu/docs/llms.txt
> Use this file to discover all available pages before exploring further.
> Full content: https://eulabel.eu/docs/llms-full.txt
> Append .md to any page URL for markdown, or send Accept: text/markdown.



Every error from an endpoint is one JSON object. Read `code` to branch, `param` to find the field, and `suggestion` to fix it. Retry only `429` and `5xx`. An unknown path or an unsupported method is [not JSON](#handle-responses-that-arent-json).

**Video: Read a 422 and fix it** (https://pub-7ea90ccdf0f545b3ad4613d72e450782.r2.dev/errors.mp4). In a terminal, a request fails with a 422, the `suggestion` field explains the fix, and the corrected request succeeds.

## Read the error object
This request leaves out the sector, so the API returns `422`.

#### cURL


```bash
curl -X POST https://api.eulabel.eu/v1/passports \
  -H "Authorization: Bearer $EULABEL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"gtin": "5609727864985", "name": "Quinta Demo Rosé", "brand": "Quinta Demo"}'
```

#### JavaScript


```javascript
const res = await fetch('https://api.eulabel.eu/v1/passports', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.EULABEL_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ gtin: '5609727864985', name: 'Quinta Demo Rosé', brand: 'Quinta Demo' }),
});
const body = await res.json();
if (!res.ok) console.error(body.error.code, body.error.param, body.error.suggestion);
```

#### Python


```python
import os
import requests

res = requests.post(
    "https://api.eulabel.eu/v1/passports",
    headers={"Authorization": f"Bearer {os.environ['EULABEL_API_KEY']}"},
    json={"gtin": "5609727864985", "name": "Quinta Demo Rosé", "brand": "Quinta Demo"},
)
body = res.json()
if not res.ok:
    print(body["error"]["code"], body["error"].get("param"), body["error"].get("suggestion"))
```


```json
{
  "error": {
    "type": "validation_error",
    "message": "Say which sector this product belongs to.",
    "code": "validation_error",
    "param": "category",
    "suggestion": "Send projectId, or category as one of: wine, battery, textile, furniture, construction, toy, detergent, steel, tyre, mattress, aluminium, food, electronics.",
    "documentationUrl": "https://eulabel.eu/docs/api-reference/endpoints/passports"
  }
}
```

| Field | Always there | Meaning |
| --- | --- | --- |
| `code` | Yes | Machine-readable code. Branch on this. |
| `type` | Yes | Same value as `code`. |
| `message` | Yes | Human-readable explanation. Don't parse it. |
| `param` | No | The field at fault. |
| `suggestion` | No | How to fix it. |
| `documentationUrl` | No | The page about it. |

A missing compliance field is not an error. `POST /v1/passports` accepts the data, saves a draft, and lists what is missing in `compliance.missingFields`. `POST /v1/products/import` adds `createdCount`, `created` and `errors` next to `error` on its `422`.

## Fix each error code
| Status | Code | Cause | Fix |
| --- | --- | --- | --- |
| 400 | `invalid_request` | The body is not valid JSON, or a CSV import is empty. | Send valid JSON or a non-empty CSV. |
| 400 | `invalid_idempotency_key` | The `Idempotency-Key` is empty, over 255 characters, or not visible ASCII. | Send a UUID. |
| 400 | `idempotency_not_supported` | You sent an `Idempotency-Key` to `POST /v1/access-grants`, whose token is never stored. | Send it without the header. |
| 401 | `authentication_required` | The API key is missing, wrong or revoked. | Send `Authorization: Bearer eul_...` with an active key. |
| 401 | `session_required` | You called `/v1/auth/api-keys` with an API key. | Manage keys in the dashboard. |
| 403 | `insufficient_permissions` | The key lacks the scope. `message` names it. | Create a key with that scope. |
| 403 | `scope_violation` | A project-scoped key reached another project, or a route that needs an organization key. | Use a key for that project, or an organization key. |
| 403 | `terms_not_accepted` | The organization hasn't accepted the Terms and Data Processing Agreement. | An owner or admin accepts them in the dashboard. |
| 403 | `forbidden` | The project belongs to another organization. | Check the `projectId`. |
| 403 | `csrf_origin_mismatch` | A cookie-authenticated request came from another origin. | Use an API key. |
| 404 | `not_found` | The ID doesn't exist or isn't yours, the ID is a `ps_` id, or the passport was withdrawn. | Use the `productId` UUID. |
| 405 | None | The route doesn't support this method. The body is empty. | Check the method in the [API reference](https://eulabel.eu/docs/api-reference/overview/introduction). |
| 409 | `duplicate_error` | The product, supplier link, domain or project slug already exists. | Don't retry. Fetch the existing one, or use `POST /v1/passports`. |
| 409 | `gtin_conflict` | Another organization holds this GTIN or its company prefix. | Use a GTIN under your prefix, or [claim the prefix](https://eulabel.eu/docs/knowledge-base/guides/gtin-ownership). |
| 409 | `category_locked` | You changed the category of a product that has a project or a passport. | Create a new product in the right sector. |
| 409 | `not_published` | You withdrew a passport that isn't live. | Check its status first. There is nothing to withdraw. |
| 409 | `already_revoked` | The access grant is already revoked. | None needed. |
| 409 | `idempotency_request_in_progress` | A request with the same `Idempotency-Key` is still running. | Wait for `Retry-After`, then retry with the same key. |
| 409 | `conflict` | The project is in the wrong state: already archived, not archived, or archived when creating a key. | Archive or restore it first. Delete needs an archived project. |
| 422 | `validation_error` | A field is missing or invalid, or a value can't be stored, such as a NUL character or JSON nested over 64 levels. | Correct `param` using `suggestion`. Don't retry unchanged. |
| 422 | `idempotency_key_reused` | The `Idempotency-Key` was used within 24 hours for a different request. | Use a new key for each new operation. |
| 422 | `domain_verification_failed` | The DNS TXT record is missing or wrong. | Add the record named in `message`, then retry. |
| 429 | `rate_limited` | The key sent over 600 requests in a minute. | Wait for `Retry-After` seconds. |
| 500 | `internal_error` | Unexpected failure. | Retry with backoff. If it continues, contact support. |
| 502 | `upstream_error` | The auth service failed on an API key route. | Retry with backoff. |

> **Warning**
> `POST /v1/products`, `POST /v1/products/{productId}/suppliers` and `POST /v1/domains` are not idempotent on their own. Sending the same thing twice returns `409 duplicate_error`. Send an [`Idempotency-Key`](https://eulabel.eu/docs/knowledge-base/guides/idempotency-and-deduplication#retry-any-post-with-an-idempotency-key) to make a retry safe.

The public passport JSON at `https://eulabel.eu/p/api/passport/{productId}` is a separate service with a flat error: `{ "error": "invalid_token" }`. It returns `401 invalid_token`, `403 insufficient_scope` and `404 not_found`.

## Handle responses that aren't JSON
These two come from the web framework, before any endpoint runs, so `await res.json()` throws on them.

| Request | Status | Body |
| --- | --- | --- |
| Unknown path, such as `GET /v1/nope` | `404` | An HTML page, with `Content-Type: text/html` |
| Unsupported method, such as `PUT /v1/passports` | `405` | Empty, with no `Allow` header |

Check the content type before you parse:

```javascript
const res = await fetch('https://api.eulabel.eu/v1/nope', {
  headers: { Authorization: `Bearer ${process.env.EULABEL_API_KEY}` },
});
const isJson = res.headers.get('content-type')?.includes('application/json');
const body = isJson ? await res.json() : null;
if (!res.ok) throw new Error(body?.error.code ?? `HTTP ${res.status}`);
```

## Retry only what can succeed
| Status | What to do |
| --- | --- |
| `429` | Wait for `Retry-After`, then retry |
| `5xx` | Back off, then retry. `POST /v1/passports` creates the product first, so a retry after a failure keeps its first `name` and `brand`. `PATCH` the product to change them |
| Other `4xx` | Fix the request. Don't retry |

This helper waits for `Retry-After` when the API sends it, and otherwise doubles the delay. It returns the last response, so you handle errors in one place.

#### JavaScript


```javascript
async function apiFetch(url, options, maxRetries = 3) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(url, options);
    const retryable = res.status === 429 || res.status >= 500;
    if (!retryable || attempt === maxRetries) return res;

    const retryAfter = Number(res.headers.get('Retry-After'));
    const seconds = retryAfter > 0 ? retryAfter : 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
  }
}

const res = await apiFetch('https://api.eulabel.eu/v1/products?limit=1', {
  headers: { Authorization: `Bearer ${process.env.EULABEL_API_KEY}` },
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
console.log(body.pagination.total);
```

#### Python


```python
import os
import time
import requests

def api_request(method, url, max_retries=3, **kwargs):
    for attempt in range(max_retries + 1):
        res = requests.request(method, url, **kwargs)
        retryable = res.status_code == 429 or res.status_code >= 500
        if not retryable or attempt == max_retries:
            return res

        retry_after = res.headers.get("Retry-After", "")
        seconds = int(retry_after) if retry_after.isdigit() else 2 ** attempt
        time.sleep(seconds)

res = api_request(
    "GET",
    "https://api.eulabel.eu/v1/products",
    params={"limit": 1},
    headers={"Authorization": f"Bearer {os.environ['EULABEL_API_KEY']}"},
)
body = res.json()
if not res.ok:
    raise RuntimeError(f"{body['error']['code']}: {body['error']['message']}")
print(body["pagination"]["total"])
```


> **Warning**
> A `POST` that returned `500` may still have been stored. Send an [`Idempotency-Key`](https://eulabel.eu/docs/knowledge-base/guides/idempotency-and-deduplication#retry-any-post-with-an-idempotency-key) on every `POST` you retry automatically, such as recording an item event. `POST /v1/passports` is safe to retry even without one.


