Skip to content
Shortcut: /, ⌘K or Ctrl+K

Handle errors

Read Polymorfa errors, decide when to retry and trace a failed request.

View as Markdown

A failed Messaging or Platform request returns an HTTP status and an error object. Branch on the stable error.code, retry only the failures that a retry can fix, and keep the request ID so you can find the request later.

A failure does not always mean nothing happened. A timeout or an unconfirmed dispatch can leave a message sent. Use idempotency keys on writes so a retry never repeats one.

Read the error object#

Every Messaging and Platform error has the same shape:

JSON
{
  "error": {
    "type": "permission_error",
    "code": "missing_scope",
    "message": "This action requires messages:write.",
    "param": null,
    "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30",
    "request_log_url": "https://www.polymorfa.com/console/acme/support-bot/logs/api?request_id=5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30"
  },
  "data": null,
  "docs": "https://docs.polymorfa.com/api/errors#missing-scope"
}
FieldUse it to
error.codeDecide what to do. Codes never change meaning, and new codes can appear, so handle unknown codes.
error.typeGroup failures: invalid_request_error, authentication_error, permission_error, billing_error, conflict_error, rate_limit_error, upstream_error or api_error.
error.messageShow or log a readable reason. The text can change; never parse it.
error.paramFind the request field that failed, or null when no field applies.
error.request_idIdentify the request in logs and support conversations.
error.request_log_urlOpen the request in the Console's request log, when the API returns it.
docsOpen the error's entry in Errors, with its fix.

Graph requests at /graph/whatsapp/... return Meta's error object instead. See Meta-compatible errors.

Decide whether to retry#

Use the status and code together:

StatusRetry?What to do
400, 405, 413, 422NoFix the request. error.param names the field.
401NoReplace the credential. A 503 credential_verification_unavailable is different: retry it.
402Noerror.type is billing_error. Match on error.code to handle the cause. For addon_required, read error.message for the add-on to activate. See Payment errors.
403NoUse a credential with the missing scope, or resolve the safety refusal named in the code.
404, 410NoCheck the identifier and that it belongs to the credential's team or project.
409Depends on the codeRead Conflicts.
429Yes, after the waitRead Rate limits.
500, 502, 503Depends on the codeRetry reads with backoff. Retry writes only with the same Idempotency-Key. For 503 idempotency_replay_unavailable, read Unavailable replay instead of blindly retrying.
504Not blindlyThe result is unknown. Read Unknown outcomes.

Back off exponentially with jitter between retries, and cap the number of attempts. Do not start parallel retries of the same request.

Conflicts #

A 409 means the resource state or your idempotency key prevented the request.

CodeWhat to do
state_conflictSomeone changed the resource after you read it. Read it again, reapply your change and send the new revision.
idempotency_in_progressWait for Retry-After, then retry with the same key and request.
idempotency_outcome_unknownCheck whether the write happened before you use a new key.
bansafe_send_outcome_unknownNever retry automatically. Reconcile delivery state first.

Reusing a key for a different request returns 422 idempotency_conflict, rather than 409. Use a new key only for the different request.

Unavailable replay #

503 idempotency_replay_unavailable means the retained receipt prevents another execution, but the exact response is unavailable. This can happen when the response cannot be retained or its replay data is lost. Keep the first response and reconcile events or the resource. Do not switch keys to resend.

Retry-After gives the wait before checking again with the same key. Waiting does not release the execution fence or guarantee that replay data becomes available. See Idempotency.

Rate limits #

Every 429 carries a Polymorfa-RateLimit-Reason header and, when the wait is known, Retry-After. Wait at least Retry-After seconds, even when X-RateLimit-Reset is earlier. The reason tells you which limit applied: request_rate is your team's API quota, whatsapp and whatsapp_new_chat_limit come from WhatsApp, and bansafe_pacing and daily_allowance come from Number safety pacing. See Rate limits and Rate-limit reasons.

Unknown outcomes #

Two errors mean Polymorfa could not confirm what happened to a Messaging write:

CodeStatusMeaning
result_unknown504The response deadline passed before the result was known. The action might have completed.
command_dispatch_failed503Dispatch was not confirmed. The action could still have been accepted.

Neither proves that the action failed. Before you send again:

  1. Check the message events, such as message.sent, message.failed and command.result, or read the resource.
  2. If the write happened, stop.
  3. If you confirm it did not happen, send it again with a new Idempotency-Key.

A retry with the original key returns the same error and never sends a second copy. See Idempotency.

Asynchronous Messaging requests#

Send Prefer: respond-async to get an answer before a linked-device command finishes. When Polymorfa applies the preference, it returns 202 with Preference-Applied: respond-async, and the result arrives later as a command.result event. A send refused after the 202 arrives as message.failed with the error code the synchronous request would have returned.

Do not assume the preference was applied without that header. Requests through an official WhatsApp Business number return their result synchronously, even when you send the header.

Find a request #

Every response carries an X-Request-Id header, and every error repeats it as error.request_id. Log it with every failure and include it when you contact support.

To correlate a request with your own logs, send your own X-Request-Id of 1 to 128 letters, digits, ., _, : or -, starting with a letter or digit. Polymorfa replaces any other value with a generated ID.

With a team key or project token, error.request_log_url opens the request in the Console. You can also search for it in Request logs. See Request IDs and log links.

Handle errors in code #

Read the status first, then error.code. In the SDK, every failed request throws a subclass of PolymorfaError: branch on the class, then on code.

cURL
curl -sS -D headers.txt -o body.json \
  https://api.polymorfa.com/messaging/support/messages/send \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Idempotency-Key: order-1042-shipped" \
  -H "Content-Type: application/json" \
  -d '{"conversation":{"phoneNumber":"+15550001111"},"content":{"text":"Your order shipped"}}' \
  -w '%{http_code}\n'

jq -r '.error.code, .error.request_id' body.json
grep -i -E '^(retry-after|polymorfa-ratelimit-reason|x-request-id):' headers.txt
Graph API
curl -sS -o body.json \
  "https://api.polymorfa.com/graph/whatsapp/v26.0/$PHONE_NUMBER_ID/messages" \
  -H "Authorization: Bearer $POLYMORFA_KEY" \
  -H "Content-Type: application/json" \
  -d '{"messaging_product":"whatsapp","to":"15550001111","type":"text","text":{"body":"Your order shipped"}}' \
  -w '%{http_code}\n'

jq -r '.error.code, .error.error_subcode, .error.fbtrace_id' body.json
TypeScript
import {
  PolymorfaError,
  PolymorfaRateLimitError,
  PolymorfaServerError,
} from "@polymorfa/sdk";

try {
  await messaging.messages.send(
    "<number-id>",
    { conversation: { phoneNumber: "+15550001111" }, content: { text: "Your order shipped" } },
    { idempotencyKey: "order-1042-shipped" },
  );
} catch (error) {
  if (error instanceof PolymorfaRateLimitError) {
    console.warn("Rate limited", error.rateLimitReason, error.metadata?.headers["retry-after"]);
  } else if (error instanceof PolymorfaServerError && error.code === "idempotency_replay_unavailable") {
    // The write was not repeated. Reconcile events or the resource; keep the key.
  } else if (error instanceof PolymorfaServerError && error.code === "result_unknown") {
    // Check message events before deciding to send with a new key.
  } else if (error instanceof PolymorfaError) {
    console.error(error.status, error.code, error.message, error.requestId);
  } else {
    throw error;
  }
}

TypeScript:

Each error has these fields:

FieldContains
statusHTTP status, when the API answered
codeThe stable error code, such as missing_scope. See Errors
messageA readable description
requestIdThe request ID. Include it when you contact support
requestLogUrlThe Console page for this request, when the API returns one
docUrlThe documentation link for code
rateLimitReasonWhich limit a 429 hit, such as request_rate or whatsapp
detailsExtra error data from the API
metadataResponse status, headers and attempt count
ClassWhen
PolymorfaValidationError400, 413 or 422: the request is invalid
PolymorfaAuthenticationError401: the key is missing, invalid, expired or revoked
PolymorfaPaymentRequiredError402: the team cannot pay for the request. The SDK never retries it
PolymorfaAuthorizationError403: the key lacks a permission, or the feature is not enabled for the team
PolymorfaNotFoundError404: the resource does not exist or the key cannot see it
PolymorfaConflictError409: the resource changed, or the keyed request is still running (idempotency_in_progress) or has an unrecorded outcome (idempotency_outcome_unknown)
PolymorfaRateLimitError429: too many requests
PolymorfaServerError5xx: the API failed
PolymorfaTimeoutErrorNo response within timeoutMs
PolymorfaConnectionErrorThe SDK could not reach the API
PolymorfaCancelledErrorYour signal aborted the request
PolymorfaConfigurationErrorInvalid client options or arguments, thrown before sending
WebhookSignatureErrorA webhook signature did not match
PolymorfaMediaIntegrityErrorDownloaded WhatsApp media failed its integrity checks

Error codes never change meaning, and the API can add new ones, so handle codes you do not know. isKnownPolymorfaErrorCode(code) tells you whether the installed SDK knows a code.

A Graph request answers in Meta's error object instead: branch on the numeric error.code and error.error_subcode, and keep error.fbtrace_id to trace the request. An operation the Number's connection cannot perform returns capability error 131026; retrying the same Graph request does not help. Each guide's Graph API statement says which connections support its task. See Connections and capability errors.

Retries in the SDK #

The SDK retries a request when both are true:

  • The request is a GET, HEAD or OPTIONS, or it has an idempotencyKey.
  • It failed with a network error, a timeout, or status 408, 409, 429 or 5xx.

It waits for Retry-After when the API sends it, up to 60 seconds; otherwise it backs off exponentially, up to 5 seconds between attempts. It retries twice by default. Set maxNetworkRetries on the client or the request to change that, or to 0 to turn retries off. It never retries a replayed result. A write without an idempotency key is sent once, because the SDK cannot tell whether the first attempt ran. Some writes create a key for each call; see Send the key.

See also#