SDK errors, retries, and timeouts

Catch the TypeScript SDK's typed errors, set up retries that follow the gateway's retry contract, and set timeouts, idempotency keys, and request IDs.

The SDK throws on any failed request, with an error class that says where it failed. Retries and timeouts are off until you turn them on. For the API's error envelope and every error code, see Errors and retries.

Error classes

Import the error classes from @cruxy/api/models/errors, and the streaming ones from @cruxy/api.

ClassThrown whenWhat it carries
CruxyErrorThe gateway answered with an error status and its JSON error envelope, from any method.code, error (the message), requestId, the envelope's detail fields, and the CruxyBaseError fields.
CruxyDefaultErrorAn error status whose body is not JSON, such as an HTML page from a proxy.The CruxyBaseError fields.
DeviceTokenPendingResponseErrordeviceLogin.pollDeviceToken got a 400: still pending, or refused for good.code (authorization_pending, access_denied, expired_token, or invalid_grant), error, errorDescription, reason, requestId.
ResponseValidationErrorA response did not match the spec, such as a missing required field.rawValue, the body as received.
SDKValidationErrorYour request failed the SDK's validation before it was sent.rawValue.
ConnectionErrorThe request could not reach the server.cause.
RequestTimeoutErrortimeoutMs passed before a response arrived.cause.
RequestAbortedErrorYour signal aborted the request.cause.
ChatStreamFrameError, IncompleteChatStreamError, ChatStreamTimeoutError, MalformedChatStreamErrorA chat stream failed after it opened; see Stream errors.

CruxyError, CruxyDefaultError, DeviceTokenPendingResponseError, and the stream errors all extend CruxyBaseError, which carries statusCode, body (the raw response text), headers, contentType, and rawResponse. None of them carries your key: the request attached to an error has no Authorization header.

A CruxyError carries the envelope's detail fields when the code sends them, among them retryAfter (seconds), resetAt, tier, model, window, limit, requiredScope, and requiredVersion.

Read the gateway's message from error, not message. A CruxyError's message is API error occurred: followed by the parsed envelope as JSON.

Branch on the code

Branch on code, never on the wording of the message:

import { Cruxy } from '@cruxy/api'
import { CruxyError } from '@cruxy/api/models/errors'
 
const cruxy = new Cruxy({ bearerAuth: process.env.CRUXY_API_KEY })
 
try {
  const { result } = await cruxy.embeddings.createEmbeddings({
    body: { model: 'cruxy-embed', input: ['The quick brown fox'] },
  })
  console.log(result.data.length)
} catch (err) {
  if (!(err instanceof CruxyError)) throw err
 
  switch (err.code) {
    case 'rate_limited':
      // Wait err.retryAfter seconds and retry, or let the SDK retry; see Retries.
      break
    case 'budget_exhausted':
      // Retrying cannot help until err.resetAt.
      break
    case 'unauthorized':
      // Fix the key; retrying cannot help.
      break
    default:
      console.error(`${err.statusCode} ${err.code}: ${err.error} (request ${err.requestId})`)
  }
}

The codes, and what each needs from you, are in Errors and retries.

Retries

Retries are off by default: a failed request throws at once. Turn them on for the whole client with retryConfig, or for one call with the retries option. The client's retryConfig covers every method, chat.stream included.

import { Cruxy } from '@cruxy/api'
 
const cruxy = new Cruxy({
  bearerAuth: process.env.CRUXY_API_KEY,
  retryConfig: {
    strategy: 'backoff',
    backoff: {
      initialInterval: 1_000,
      maxInterval: 20_000,
      exponent: 1.5,
      maxElapsedTime: 60_000,
    },
    retryConnectionErrors: true,
  },
})
 
const { result } = await cruxy.models.listModels()
console.log(result.data.length)
  • What is retried: a response whose status is in retryCodes (by default 429, 500, 502, 503, and 504) and whose error code the gateway's retry contract says to retry. With retryConnectionErrors: true, attempts that could not connect or that passed timeoutMs are retried too. Set retryCodes on a call to change the statuses for that call.
  • How long it waits: exponential backoff with up to a second of random jitter on each wait. When backoff is left out, the waits grow from initialInterval 500 ms by exponent 1.5, capped at 60 s each and an hour in total. A Retry-After or retry-after-ms header on the response sets the wait instead, capped at maxInterval.
  • What is resent: the same request, headers included, so an idempotencyKey is reused on every attempt.

Which codes are retried

The SDK retries these codes, and no others:

rate_limited, limits_unavailable, credits_unavailable, headless_concurrency_limit, upstream_overloaded, model_unavailable, all_models_unavailable, service_unavailable, upstream_timeout, server_shutting_down, and internal_error.

So a retryable status is still not retried when its code says waiting cannot help:

  • Budget and spend-cap 429s are not retried: budget_exhausted, message_limit_reached, key_spend_cap_exceeded, workspace_spend_cap_exceeded, and credits_exhausted. They clear only at resetAt, or when the cap changes, which can be days away. The SDK throws the CruxyError at once; read resetAt and decide. See Rate limits and budgets.
  • upstream_error (502) is not retried.
  • A code the SDK does not know is not retried.

A response with no Cruxy error envelope, such as an HTML 502 from a proxy, is retried by its status alone. The list is exported as RETRYABLE_ERROR_CODES, with isRetryableErrorCode(code), from @cruxy/api, so your own retry logic can give the same answer.

Streams

chat.stream retries only while it opens: a 429 or 5xx before any bytes arrive is retried under the same rules. Once the stream opens it is never resent for you, because a resent stream would repeat output. A stream that fails after it opens throws, and ChatStreamFrameError.retryable gives the same answer for its code as the list above. To retry it yourself, send the request again with the same idempotencyKey.

Timeouts

There is no timeout by default. On every method except chat.stream, timeoutMs on the client, or on one call, bounds the whole call: an attempt that runs longer throws a RequestTimeoutError. When you pass your own signal, timeoutMs does not apply to that call.

On chat.stream, timeoutMs bounds only the wait for response headers, so it never cuts off a stream that is still sending. Bound the body with idleTimeoutMs and totalTimeoutMs; see Stream timeouts. For the gateway's own deadlines, see Deadlines and timeouts.

Idempotency

idempotencyKey sends Idempotency-Key on chat.createChatCompletion, chat.stream, embeddings.createEmbeddings, rerank.rerankDocuments, moderations.createModeration, and files.uploadFile. Mint one key per logical request and reuse it on every retry, so a request the gateway already completed is not run and billed again:

import { randomUUID } from 'node:crypto'
import { Cruxy } from '@cruxy/api'
 
const cruxy = new Cruxy({
  bearerAuth: process.env.CRUXY_API_KEY,
  retryConfig: { strategy: 'backoff', retryConnectionErrors: true },
})
 
const { result } = await cruxy.chat.createChatCompletion({
  idempotencyKey: randomUUID(),
  body: { model: 'epos', messages: [{ role: 'user', content: 'Say hello.' }] },
})
console.log(result.message.content)

A stream is not replayed from the key; how the gateway bills a retried stream is in Errors and retries. How it treats the key on every route is in Retry safely with Idempotency-Key.

Request IDs

Every response carries an X-Request-Id header, and most bodies carry the call's request ID too. Log it, and quote it when you email [email protected] about a call:

WhereHow to read it
Any responseheaders['x-request-id']?.[0]
chat.createChatCompletionresult.requestId
chat.streamstream.requestId, from the start frame
embeddings.createEmbeddings, rerank.rerankDocumentsresult.cruxy.requestId
A CruxyError or ChatStreamFrameErrorerr.requestId
A CruxyDefaultErrorerr.headers.get('x-request-id')

To send your own ID, pass it as a header on the call, such as { headers: { 'X-Request-Id': 'order-1234-attempt-1' } }. The rules for what the gateway accepts, and what else to send with a report, are in Request IDs and metadata.

Was this page helpful?