Error handling

A failed API request returns an HTTP error. A successfully queued upload can separately end with classification.status failed if processing fails. Handle both paths.

Request errors

HTTP errors return:

{
  "code": "validation/invalid-request",
  "message": "Too big: expected number to be <=100",
  "requestId": "k3v9q2x7m1p4r8t6w5z0",
  "details": {
    "issues": [{ "path": "pageSize", "message": "Too big: expected number to be <=100", "code": "validation/too-big" }]
  }
}
FieldMeaning
codeA stable code to branch on, such as 404 asset/not-found. CalmLens can add codes to any endpoint, so handle an unknown code by its HTTP status.
messageAn explanation for developers. Its wording can change, so don't match on it.
requestIdThe request's ID, the same as the X-Request-Id header.
detailsStructured information that depends on the code, such as issues for a validation error or retryAfterSeconds. It is an empty object when there is none.

Invalid input returns 400 validation/invalid-request, however many problems the request has. details.issues lists each one with its path, message and an issue code: validation/invalid-type, validation/too-small, validation/too-big, validation/invalid-format, validation/invalid-value or validation/unknown-field.

The SDKs return structured API errors. Handle errors by their code; log the message and details when debugging.

import { CalmLensError } from "calmlens";

try {
  await client.assets.retrieve({ assetId });
} catch (error) {
  if (error instanceof CalmLensError && error.code === "asset/not-found") {
    return undefined;
  }
  throw error;
}

Some errors never reach the API: the SDKs check arguments and content before sending, and report a timeout, cancellation or connection failure when no response arrives. A content check uses the code the API would return, such as 415 upload/unsupported-type, but the error has no HTTP status or request ID, and each SDK marks it as raised locally. Branch on the code rather than the status, so both kinds are handled the same way.

Every response from CalmLens, successful or not, carries an X-Request-Id header that identifies the request in CalmLens logs. Log it with failed requests and include it when you contact support.

Retry reads after network failures and server errors with capped exponential backoff. Before retrying a write, follow Retrying requests safely: a timed-out request may already have succeeded. Do not automatically retry validation errors. For multipart part errors, see Retrying parts.

Set a User-Agent

Send a User-Agent header that names your app, such as my-app/1.0, with every request to the API and the CDN. The SDKs send their own.

Some HTTP clients' default values, such as those of Python's urllib and Java 8's HttpURLConnection, are refused before the request reaches CalmLens. The response is 403 with the text/plain body error code: 1010, rather than the JSON body above, and it has no X-Request-Id. It doesn't mean your API key or permissions are wrong. Set the header and send the request again.

Retrying requests safely

A request that timed out may have succeeded. Retrying a create or moderate request could then create a second asset that counts towards your usage. To prevent this, send an Idempotency-Key header on asset uploads (POST JSON uploads, POST raw file uploads and POST multipart starts) on POST /assets/:assetId/part, and on POST decisions and POST hash list entries, and send the same key with every retry of that request:

Idempotency-Key: 4f9a1c2e-8b7d-4e61-9a35-0c2b7f1d6e80
  • Use a new key for each request. A UUID works well. Keys can be up to 255 printable ASCII characters (or 240 characters when an SDK splits a multipart upload, to leave room for the :part-<n> suffix); anything else returns 400 idempotency/invalid-key.
  • A retry returns the saved response. When the first request succeeded, a retry with the same key gets its response for 24 hours, with the header Idempotent-Replayed: true, and nothing runs again.
  • The key belongs to one request. Reusing a key for a different request (another path, other query parameters or another body) returns 409 idempotency/key-reused. Raw uploads are compared by their query parameters, their options part and Content-Length rather than by their bytes; a retry may use a new form boundary.
  • Concurrent retries wait their turn. While the first request is still running, a retry returns 409 idempotency/request-in-progress with a Retry-After header. Wait that many seconds and retry with the same key to receive the result.
  • Failures are not saved. If the first request failed, the key is freed and a retry runs the request again, so you can fix the problem and retry with the same key.
  • Keys are scoped to your API key. A key sent with one API key never matches a request sent with another.

To check a multipart upload before resending its first part, send the original start request with Idempotency-Replay-Only: true, the same Idempotency-Key, query parameters and options part, and an empty file part. A matching upload returns its current asset and upload.partsReceived; no matching upload returns 204 without creating or reserving anything. Changed metadata returns 409 idempotency/key-reused. The Go SDK performs this check when a split upload has an explicit IdempotencyKey, then sends only the missing parts. A fresh explicit key adds one small lookup request before uploading.

A unique externalId also protects against duplicates, but unlike an idempotency key it doesn't return the first response: the error's details.assetId names the existing asset, so retrieve it instead.

Bound a call someone is waiting on

An SDK's request timeout applies to each attempt, and its retries add backoff waits, so one call can take several attempts' time. When a person is waiting, as for a comment checked before it is posted, give the call a deadline with the SDK's deadline request option (deadlineMs in JavaScript; see your SDK's page for its name). It covers every attempt and wait, and when it passes the call fails with sdk/timeout and nothing is retried. Choose it from how long your page can wait. On sdk/timeout, hold the content as pending and apply its decision from the webhook instead of publishing it unchecked. A call stopped by its deadline may still have been received, so send it with an Idempotency-Key if you retry it later.

Rate limits

If a request is throttled, it returns 429 with a Retry-After header giving the number of seconds to wait before retrying. Uploads have their own limits:

ErrorReturned when
403 usage/free-uploads-exhaustedThe organisation has used all its free uploads without setting up billing.
402 usage/uploads-pausedThe upload would pass one of the organisation's usage limits. details.reason says which.
429 upload/rate-limit-reachedThe organisation started more than 100 uploads in 10 seconds. See Upload rate.
403 remote-url/not-allowedThe URL is on a domain the project doesn't accept.

File-size and multipart constraints return their documented upload/* errors.

Choose a recovery action

FailureExamplesRecovery
Missing or invalid credentials, or insufficient access401 api-key/invalid, 403 api-key/project-mismatch, 403 auth/permission-deniedFix credentials and permissions before retrying. Alert whoever runs the integration: a retry won't succeed.
403 with the plain text body error code: 1010Set a User-Agent that names your app, then retry.
Validation or unsupported input400 validation/invalid-request, 415 upload/unsupported-type, 413 upload/too-large, 422 image/invalidCorrect the request or file. For a user's file, tell them what to change; never retry it unchanged.
An externalId already in use409 asset/duplicate-external-idThe content was already uploaded. Retrieve the asset that details.assetId names; while the first upload is still in progress there are no details, so retry shortly.
Network timeout or server failuresdk/timeout, sdk/transport-error, 500, 502, 503, 504Retry with capped backoff and the same Idempotency-Key; without one, check whether a write succeeded before repeating it.
Throttled (429) or request still in progress429 upload/rate-limit-reached, 409 idempotency/request-in-progressWait for the Retry-After delay, then retry.
Idempotency key reused for a different request409 idempotency/key-reusedSend the new request with a new key.
Usage limits reached403 usage/free-uploads-exhausted, 402 usage/uploads-pausedUploads fail until an owner sets up billing or reviews the organisation's usage limits in Billing (details.reason says which applies). Alert whoever runs the integration, and hold content rather than publishing it.
Multipart conflict409 upload-part/invalid-number, 409 upload/use-upload-partCheck the expected part number or restart the upload.

Processing failures

A queued request can succeed while classification later fails. Watch for classification.status failed through retrieval or the asset.failed event; do not publish that content. Inspect its classification.failureReason (see Failure reasons), correct the input when needed, then retry an eligible asset. Follow Recover from processing failure for retry eligibility, the API operation and when to submit a new copy.

Last updated

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies