Skip to Content

Error Handling

Every failure throws FoirRequestError. It is the same class @foir/sdk/client throws, re-exported from @foir/sdk/data so you do not have to import a second subpath to catch it.

import { FoirRequestError } from '@foir/sdk/data'; try { const post = await foir.post.findUnique({ naturalKey: slug }); } catch (err) { if (err instanceof FoirRequestError) { console.error(err.message, err.status, err.graphQLErrors); } throw err; }
PropertyType
messagestringPrefixed [foir], with the server’s own sentence appended
statusnumber | undefinedHTTP status, when it failed at the HTTP layer
graphQLErrorsreadonly { message, path? }[] | undefinedThe parsed error list
causeunknownThe underlying error, for network failures

Two places a call can fail

Some faults are caught before the request, while the client is printing your document. Those never reach the network, carry no status, and name the thing you asked for that the generated description does not have:

[foir] cost_breakdown has no op "findFirst" for this credential — re-run `foir types`

The rest come back from the server, and the client reads the body rather than surfacing a bare status:

[foir] HTTP 400 Bad Request: Cannot query field "bogus" on type "CostBreakdown"

Every caller-fixable fault is a 400 with a sentence naming what was wrong.

Faults the client catches first

These are all FoirRequestError with status === undefined, and all of them mean the same class of thing: your generated description and your call disagree. The fix is usually foir types.

The model or operation is not on this credential

[foir] no model "nope" in this credential's surface — re-run `foir types` [foir] cost_breakdown has no op "create" for this credential — re-run `foir types`

A model you cannot see and a model that does not exist are the same fact from where you are standing, so they read the same. If you generated types from this key you should have caught this at compile time; reaching it at runtime usually means the types are stale.

An argument the operation does not take

[foir] cost_breakdown.findUnique does not take an argument "first" — it takes contexts, id, locale, naturalKey, preview

The types reject undeclared arguments too. TypeScript’s excess-property check does not fire when an object literal is inferred into a generic parameter, so the client types every undeclared key as never to put the check back — findUnique({ id, first: 10 }) is a compile error on first.

_id cannot be omitted

[foir] omit "_id": "_id" is required for correctness and cannot be removed

The generated type excludes _id from omittable keys, so a typed call cannot produce this.

pick and omit together

[foir] cost_breakdown.findMany: "omit" and "pick" are mutually exclusive — pass one or the other

An unknown relation in include

[foir] include "nope": tilly_block has no such relation — re-run `foir types` if the model has changed

include is validated against the relations your manifest published. This is also why you pass true and never false — a false is still a key.

Nothing left to select

[foir] cost_breakdown.findUnique: the selection is empty after applying pick/omit — a GraphQL selection set cannot be empty

The description is missing a piece

[foir] the selection tree names the union "Block", which is not in selectionUnions — re-run `foir types`, or pass selectionUnions alongside selections

That one is worth recognising: it means selections was passed without selectionUnions. Pass every const the generated module exports — see the generated module.

Faults the server returns

Missing or invalid credentials

{ "errors": [{ "message": "API key or a signed-in person's token required", "extensions": { "code": "UNAUTHENTICATED", "requestId": "082b5610f73d2bec" } }] }

HTTP 401. No x-api-key header, and no signed-in person’s token that verifies. A key the platform does not recognise is answered Invalid or expired API key, in the same shape.

Every rejection made before your query runs — bad credential, wrong kind of key, throttled — comes back in this shape, with an extensions.code to branch on and a requestId worth quoting in a support request. The full code list is in Errors & Rate Limits.

A visitor asks for what the key does not give

{ "errors": [{ "message": "missing required scope: records:read (this key holds it and gives it to nobody who is not signed in: name it in the key's baseline_grants, or sign the caller in)", "extensions": { "code": "PERMISSION_DENIED" } }] }

A key gives a caller with nobody signed in only what its second list names, and Foir fills nothing in. Where your publishable or server key holds a permission and does not give it, a visitor’s call is refused with the permission’s name and that sentence after it. Name the permission on the key’s list of what it gives (a key’s two lists), or forward the signed-in user’s bearer if the call is theirs to make.

A refusal for a permission the key does not hold at all, or one a signed-in user’s role does not grant, is the same message without the words in brackets. Both carry extensions.code PERMISSION_DENIED, and the permission’s name always comes first in the message. See Authorization.

Rate limited

{ "errors": [{ "message": "Rate limit exceeded", "extensions": { "code": "RATE_LIMITED", "requestId": "5327b7bbd8c825ce", "retryAfter": 1800 } }] }

HTTP 429. The key has spent its hourly allowance. This one is retryable, unlike every other 4xx — see Retrying.

Unexpected response shape

[foir] the response has no "costBreakdowns" field (got costBreakdown)

A typed operation prints exactly one root field and the client reads back the name it asked for. If the response does not carry it, saying so beats returning undefined.

Network failure

[foir] network error

err.cause holds the underlying error and err.status is undefined. This is the one to distinguish when deciding whether to retry.

Partial results

A response can carry both data and errors. GraphQL nulls a failed field and propagates upward to the nearest nullable parent, so a partial success is a real outcome:

{ "data": { "tillyBlock": { "_id": "a3pr8x0j10rigx8u6t1xthbr", "noteId": null } }, "errors": [{ "message": "Cannot return null for non-nullable field TillyNote._createdAt.", "path": ["tillyBlock", "noteId", "_createdAt"] }] }

The HTTP status is 200. A relation you included can come back null with an explanation in errors while the rest of the record is fine. path tells you exactly which field failed.

This is the shape to expect when an include brings back a related record whose non-nullable field resolves null: complete-by-default selects every scalar on the related model, so there is no narrowing that dodges it. See include.

Retrying

Retry on status === undefined (network), on 5xx, and on 429. Do not retry any other 4xx — those are faults in the request and will fail identically next time.

429 is the exception that matters, and it is easy to get wrong because it sits among the statuses that are otherwise permanent. It means your key has spent its hourly allowance; the request is fine and will succeed once the window moves. A client that treats it as a permanent 4xx fails on the first attempt for as long as the key stays saturated, and if the caller then renders nothing on a failed read, the whole site serves empty pages while the API is healthy.

Honour the wait the server gives you rather than guessing. It arrives twice, as extensions.retryAfter on the error and as the Retry-After header, in seconds:

function retryDelayMs(err: FoirRequestError, attempt: number): number | null { if (err.status === undefined || err.status >= 500) { return 2 ** attempt * 100; // network or server fault: plain backoff } if (err.status === 429) { const retryAfter = err.graphQLErrors?.[0]?.extensions?.retryAfter; return typeof retryAfter === 'number' ? retryAfter * 1000 : 60_000; } return null; // any other 4xx: your request is wrong, retrying will not fix it } async function withRetry<T>(fn: () => Promise<T>, attempts = 3): Promise<T> { for (let i = 1; ; i += 1) { try { return await fn(); } catch (err) { const delay = err instanceof FoirRequestError ? retryDelayMs(err, i) : null; if (delay === null || i >= attempts) throw err; await new Promise((r) => setTimeout(r, delay)); } } }

A retryAfter on an hourly window can be most of an hour, which is longer than any request can reasonably wait. Treat a 429 you cannot wait out as a failure worth surfacing, not as an empty result: serve stale content if you have it, and return a 503 if you do not. A 503 says the site is degraded, which is true. A 404 says the content does not exist, which is not.

Watch X-RateLimit-Remaining so you find out before it happens; see Errors & Rate Limits. Depth and complexity limits apply to a printed document exactly as they do to one you wrote — see query complexity limits, and use pick if a complete-by-default read on a deep model runs into them.

Last updated on