Errors

Handle errors with instanceof and error.code. Use the code to decide what to do; the message explains the problem to the user.

For API errors, error.code matches details.code in the response.

import { ConflictError, PlaticApiError } from "platic-sdk";

try {
  await platic.agents.rollback(agent.id, { versionId: "v3" });
} catch (error) {
  if (error instanceof ConflictError && error.code === "NOT_PREVIOUSLY_PUBLISHED") {
    console.log("v3 was never published; nothing changed");
  } else if (error instanceof PlaticApiError) {
    console.error(`${error.request.operation}: ${error.status} ${error.code} ${error.message}`);
  } else {
    throw error;
  }
}

The codes are listed in Errors and on each endpoint page.

Error from the API

All SDK errors are instances of PlaticError. If the API returns an error response, you receive a PlaticApiError with these fields:

FieldTypeWhat it is
statusnumberThe HTTP status.
codestringThe stable error code, such as NOT_FOUND.
messagestringA sentence for people.
detailsobjectExtra data for the code: issues, available, status and others.
requestobjectoperation, method, path and attempts (how many times it was sent).
retryAfterMsnumber or nullThe Retry-After of the answer, in milliseconds.
wwwAuthenticatestring or nullThe WWW-Authenticate header of a 401, for OAuth clients.

The class depends on the HTTP status:

StatusClassNotes
400, 413InvalidRequestErrorissues and fields name what was refused.
401AuthenticationErrorMissing, wrong, revoked or expired credential.
403PermissionDeniedError
404NotFoundErrorAlso for something that belongs to another workspace.
410GoneErrorA subclass of NotFoundError. Also an expired conversation search (SEARCH_SESSION_EXPIRED).
409ConflictErrorNever retried, except two short-lived conflicts of conversation actions.
412PreconditionFailedErrorcurrentVersion: the expectedVersion of a conversation action is out of date.
422InvalidConfigErrorA subclass of InvalidRequestError.
429RateLimitErrorretryAfterMs says how long to wait.
500InternalServerError
502, 503, 504ServiceUnavailableError

Any other status is a plain PlaticApiError. An answer that is not the API's shape has code: "UNEXPECTED_RESPONSE".

Conversation errors

Conversation calls use the same classes, with codes of their own. The full list is in Errors in the API.

import { ConflictError, PreconditionFailedError } from "platic-sdk";

const { data, meta } = await platic.conversations.get("conv_123", { fields: ["assigneeIds"] });
try {
  await platic.conversations.assignees.set(
    "conv_123",
    { assigneeIds: [...(data.assigneeIds ?? []), "ana@acme.com"] },
    { expectedVersion: meta.resourceVersion },
  );
  await platic.conversations.archive("conv_123");
} catch (error) {
  if (error instanceof PreconditionFailedError) {
    // Nothing changed: read the conversation again, decide again and repeat.
    console.log("It changed since it was read; current version:", error.currentVersion);
  } else if (error instanceof ConflictError && error.code === "CASE_OPEN") {
    console.log("Close these cases first:", error.caseIds);
  } else {
    throw error;
  }
}
ClassCodesWhat the error carries
InvalidRequestErrorINVALID_REQUEST, INVALID_FIELD, INVALID_INCLUDE, INVALID_FILTER, INVALID_CURSORissues; allowed lists the accepted fields or include values.
PermissionDeniedErrorFORBIDDEN, INSUFFICIENT_SCOPEThe credential can't read conversations, or can't change them.
NotFoundErrorCONVERSATION_NOT_FOUND, MESSAGE_NOT_FOUND, NOT_A_CONVERSATIONA conversation out of the credential's reach answers like one that doesn't exist.
GoneErrorSEARCH_SESSION_EXPIREDStart the search again without pageToken.
ConflictErrorCASE_OPEN, CONVERSATION_ARCHIVED, CONVERSATION_SPAM, CONVERSATION_BUSY, CONVERSATION_CHANGED, STATUS_TRANSITION_NOT_ALLOWED, THREAD_CLOSED, AGENT_NOT_ACTIVE, NO_ACTIVE_AGENT, AGENT_STOPPING, ASSISTANT_CONTINUATION_INVALID, IDEMPOTENCY_KEY_REUSED, IDEMPOTENCY_IN_PROGRESScaseIds for CASE_OPEN.
PreconditionFailedErrorVERSION_MISMATCHcurrentVersion. Never retried.
InvalidConfigErrorUNKNOWN_TAG, TOO_MANY_TAGS, INVALID_ASSIGNEE, TOO_MANY_ASSIGNEESunknownTags (and details.availableTags), invalidAssigneeIds.
ServiceUnavailableErrorSEARCH_UNAVAILABLE, CONTINUE_FAILED, ACTION_FAILEDdetails.retryable: true.
  • The SDK retries some of them for you. SEARCH_UNAVAILABLE, CONTINUE_FAILED and ACTION_FAILED are retried like any other 503, and an action keeps the same request on every attempt, so it is applied once. CONVERSATIONS_RETRYABLE_ERRORS lists these codes.
  • Two conflicts are asked again, up to maxRetries times: IDEMPOTENCY_IN_PROGRESS (an earlier attempt of the same call is still running) and, for resume and wait, AGENT_STOPPING (a previous reply is still stopping). Every other ConflictError is thrown at once.
  • A bulk call doesn't throw for one conversation. Each failed item has ok: false and its error.code.

Errors without an answer

ClassWhen
PlaticConnectionErrorNo answer arrived. A change may have been applied: read the resource before trying again.
PlaticTimeoutErrorA subclass of PlaticConnectionError. Every attempt exceeded timeoutMs.
PlaticAbortErrorYour own signal ended the call. It is not retried. The signal's reason is the cause.
PlaticUsageErrorThe SDK cannot send the call: a missing id, an option out of range, a missing apiKey. Nothing was sent.

Errors of the waits and uploads

ClassWhen
FileJobTimeoutErrorThe wait for files.waitForJob expired. Includes lastJob, fileId, uploadId and waitedMs. The job continues.
EvalRunTimeoutErrorThe wait for agents.evals.runs.wait expired. Includes lastLaunch. The run continues.
ChannelConnectionTimeoutErrorThe wait for channels.connections.wait expired. Includes lastConnection.
PlaticUploadErrorThe bytes of a large file did not reach their upload session. Has fileId, uploadId and the storage status.
WebhookVerificationErrorA webhook delivery failed verification. Has reason. See Webhooks.

A file job that fails is returned, not thrown: check job.status === "failed" and read job.error.

Validation errors

InvalidRequestError lists each problem in error.issues, as { path, message }:

import { InvalidRequestError } from "platic-sdk";

try {
  await platic.agents.create({ name: "" });
} catch (error) {
  if (error instanceof InvalidRequestError) {
    for (const issue of error.issues) console.error(`${issue.path.join(".")}: ${issue.message}`);
  } else {
    throw error;
  }
}

Handle the common cases

import { NotFoundError, PlaticConnectionError, RateLimitError } from "platic-sdk";

try {
  await platic.agents.publish(agentId);
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log("That agent does not exist in this workspace");
  } else if (error instanceof RateLimitError) {
    console.log(`Slow down; try again in ${error.retryAfterMs ?? 0} ms`);
  } else if (error instanceof PlaticConnectionError) {
    // The publish may have gone through: read before you repeat it.
    const { publication } = await platic.agents.publication.get(agentId);
    console.log("Live version:", publication.versionId);
  } else {
    throw error;
  }
}

You can receive RateLimitError after retries run out, if the call isn't retried, or if Retry-After exceeds the allowed wait. See Retries.

Data the SDK hides

If a response or network error includes your API key, a secret's value or a webhook's signing secret, the SDK replaces it with [REDACTED] before creating the error message and details.

Next steps