Skip to content
providerkit
GitHub

Errors

An error only ever answers one question: what do I do now? So the taxonomy is organised by the fix, not by the vendor or the status code.

isTransient("overload"); // true

Import and setup. A transient kind can pass with time. It does not prove that a request is safe to repeat. Try the classifier with a response body.

Install @providerkit/core with the Core quickstart, then import:

import { isTransient, ProviderError, isRetryable } from "@providerkit/core";

Use ProviderError.from(providerId, raw) to normalize a caught error. Use its kind to choose a remedy. Use isRetryable(err) to check the per-error retry policy, then apply the stream commitment and paid-call rules. An emitted chunk forbids a stream replay even if the error itself is retryable.

Kind What fixes it
aborted Nothing. The caller pressed Stop. This is not a failure.
timeout A deadline expired. Retry only when the call’s policy allows it.
network The connection failed. Check whether work finished before repeating it.
overload Retry, or fall back to another model.
rate Wait out the window, or rotate the key or model.
quota Top up, or wait for the reset. Retrying will not help.
entitlement Change the plan. A new key and a top-up both fail here.
auth Fix the credential. Every retry lands the same.
model Use a model this endpoint actually serves.
context Send less. Compact the conversation. Waiting fixes nothing.
content Review the prompt or answer blocked by a safety filter.
invalid Check the request and output limit before trying again.
unknown Inspect the provider’s message in trusted diagnostics.

isTransient covers timeout, network, overload and rate. isBackupEligible covers overload and rate, the two where a different model is a real fix.

Rather than checking status codes and error kinds manually across loops, isRetryable evaluates any caught error or response:

import { isRetryable } from "@providerkit/core";
if (isRetryable(err)) {
// The error allows retry; stream commitment and paid-call rules still apply.
}

Order of decision:

  1. Caller aborts (AbortSignal) are never retryable.
  2. An explicit shouldRetry directive on ProviderError (honoring the server’s x-should-retry header) wins over default classification.
  3. Non-retryable kinds (quota, context, model, entitlement, content, invalid) return false.
  4. Excessive waits (retryAfterMs > maxWaitMs, default 60s) return false. Long cooldowns belong to outer fallbacks, not backoff loops.
  5. Transient kinds and transport failures (fetch failed, socket drops, TLS glitches) return true.

Parsing context overflows: parseContextOverflow

Section titled “Parsing context overflows: parseContextOverflow”

When a prompt or max_tokens exceeds the model’s window, Anthropic and gateways report the exact numbers:

import { parseContextOverflow } from "@providerkit/core";
const overflow = parseContextOverflow(err);
// { inputTokens: 188059, maxTokens: 20000, contextLimit: 200000, excessTokens: 8059 }
if (overflow) {
// Dynamically lower maxTokens or compact history by the excess margin before retrying
}

Running out of credit arrives as 429 from OpenAI (insufficient_quota), 402 from some gateways, 403 from others, and 400 from Moonshot with a Chinese-language body. Retrying an empty balance is pure waste, and status alone tells you to do exactly that.

The reverse trap is worse. A 429 is usually a throttle, where waiting is the whole fix. But a context overflow also arrives as 400 (and sometimes 429), where waiting fixes nothing and the only cure is sending less.

So the classifier reads the body before the status for 4xx. The body says what is actually wrong; the status says only how the vendor chose to file it.

A status can also point at the wrong fix when nothing is about money. Google’s OpenAI-compatible endpoint answers a bad key with a 400 that says Please pass a valid API key. That is auth, so a key pool tries its next key. A Google model that answers one turn only says Multiturn chat is not enabled, also as a 400: that is model, and a fallback chain moves on to the next model. Z.ai answers a model your plan does not include with a 403 and the code [1311] (当前订阅套餐暂未开放…权限). The key works, so that is entitlement, not auth, and no key pool benches it.

A dead socket carries no HTTP response. Node wraps the real reason several layers deep, so the useful code sits on cause.cause.cause. isTransportFailure walks the cause chain five levels looking for the signatures: ECONNRESET, UND_ERR_SOCKET, fetch failed, and friends.

Miss that walk and every transient network blip reads as a permanent failure, which is how a run dies on a hiccup that a single retry would have cleared.

The adapters don’t rely on the walk for a request that got no answer at all. Every fetch rejection that isn’t your own abort is network, whatever its wording. Each runtime words that failure its own way, and one wording nobody had listed used to end the run.

An SSE response commits to 200 the moment its headers go out. Everything that goes wrong after that (a throttle, an upstream outage, a prompt the backend only measured once it started) has nowhere to be but the body.

Every shape does this, in its own dialect: a {"error":…} frame on the OpenAI shape and the gateways in front of it, an error event on Anthropic, response.failed on Responses, a bare google.rpc.Status on Gemini. All four adapters read theirs and throw a classified ProviderError, the same one a pre-body failure would have produced.

This is the failure mode worth knowing about even if you never call the helper yourself, because the version that goes unread is invisible: the payload matches no branch, the loop skips it, and the turn ends as a successful, zero-token completion. Nothing to retry, nothing in the log, and a key pool that never rotates off a spent key.

import { streamError } from "@providerkit/core";
// Writing your own adapter? This is the branch to keep.
if (payload.error) throw streamError("my-gateway", payload.error);

A number in that payload counts as an HTTP status only from 400 to 599. Vendors put their own codes in the same field: Z.ai’s 1113 is an empty balance, and read as a status it landed on overload instead of quota. With no status, the error’s type stands in for one: invalid_request_error counts as a 400 and rate_limit_error as a 429. The body’s own words still come first, as they do everywhere else.

unknown is floored to overload here and nowhere else: a stream that dies after its headers is by construction a transient upstream fault, and unknown is never retried. Only an error with no status and no type it knows gets there. Everything the body does name keeps its own kind.

parseRetryAfterMs reads the wait from a Retry-After header or Gemini’s retryDelay field. If Gemini gives the wait only in the message, Please retry in 3.365734019s. sets err.retryAfterMs to 3366. A delay in the header or field takes precedence over the message.

A long one is information, not just a delay: a wait measured in hours is a usage window, not a blip, and a run is usually better off failing fast with the reset time than sleeping into the same wall.

class ProviderError extends Error {
readonly provider: string;
readonly kind: ErrorKind;
readonly status?: number;
readonly code?: string;
readonly retryAfterMs?: number;
readonly body?: string; // may contain private request data
readonly shouldRetry?: boolean;
get isTransient(): boolean;
get isBackupEligible(): boolean;
static from(provider: string, err: unknown): ProviderError;
}

ProviderError.from is idempotent: passing one back in returns it unchanged, so wrapping at several layers is safe.

Inspect body in trusted diagnostics when a failure is unknown. A vendor message can echo private request data, so do not send it to a browser or public log without checking it.

A vendor’s error can quote what you sent. message keeps up to 500 characters of its reply and body up to 2,000, and both end up in your logs and in every run an agent saves. To leave them out, pass redactErrors: true:

import { createPresetProvider } from "@providerkit/core";
const provider = createPresetProvider("openrouter", { apiKey, redactErrors: true });

Each error that provider throws keeps its kind, status, code and retry hints, and loses the rest. A context overflow also keeps its token counts, so parseContextOverflow still reads them:

err.message; // "openrouter: the model call failed (rate, HTTP 429). The error text is left out because redactErrors is on."
err.body; // undefined
err.cause; // undefined

Retries, fallback pools and key pools read only what stays, so they make the same choices. A code stays only when it is one short word, like overloaded_error, because a vendor that puts a sentence there could be quoting you. The package’s own wording goes too, for a refused option or a stream cut short, so a redacted log says only the kind, the status, the code and an overflow’s token counts. Turn it off while you debug. It is off by default, because the words usually name the fix.

All four adapters take it, and so do createPresetProvider and a registry connection. A models chain and fallbacks specs inherit it. A provider you built yourself keeps its own setting, so build it with redactErrors: true too.

Speech always works this way, because its errors can repeat the text you asked it to read out. Transcription keeps the vendor’s words: what you sent is audio, which no error repeats, and the words often name the fix (“Invalid file format. Supported formats: …”).