Handle errors
Read Polymorfa errors, decide when to retry and trace a failed request.
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:
{
"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"
}| Field | Use it to |
|---|---|
error.code | Decide what to do. Codes never change meaning, and new codes can appear, so handle unknown codes. |
error.type | Group failures: invalid_request_error, authentication_error, permission_error, billing_error, conflict_error, rate_limit_error, upstream_error or api_error. |
error.message | Show or log a readable reason. The text can change; never parse it. |
error.param | Find the request field that failed, or null when no field applies. |
error.request_id | Identify the request in logs and support conversations. |
error.request_log_url | Open the request in the Console's request log, when the API returns it. |
docs | Open 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:
| Status | Retry? | What to do |
|---|---|---|
400, 405, 413, 422 | No | Fix the request. error.param names the field. |
401 | No | Replace the credential. A 503 credential_verification_unavailable is different: retry it. |
402 | No | error.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. |
403 | No | Use a credential with the missing scope, or resolve the safety refusal named in the code. |
404, 410 | No | Check the identifier and that it belongs to the credential's team or project. |
409 | Depends on the code | Read Conflicts. |
429 | Yes, after the wait | Read Rate limits. |
500, 502, 503 | Depends on the code | Retry reads with backoff. Retry writes only with the same Idempotency-Key. For 503 idempotency_replay_unavailable, read Unavailable replay instead of blindly retrying. |
504 | Not blindly | The 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.
| Code | What to do |
|---|---|
state_conflict | Someone changed the resource after you read it. Read it again, reapply your change and send the new revision. |
idempotency_in_progress | Wait for Retry-After, then retry with the same key and request. |
idempotency_outcome_unknown | Check whether the write happened before you use a new key. |
bansafe_send_outcome_unknown | Never 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:
| Code | Status | Meaning |
|---|---|---|
result_unknown | 504 | The response deadline passed before the result was known. The action might have completed. |
command_dispatch_failed | 503 | Dispatch was not confirmed. The action could still have been accepted. |
Neither proves that the action failed. Before you send again:
- Check the message events, such as
message.sent,message.failedandcommand.result, or read the resource. - If the write happened, stop.
- 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 -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.txtcurl -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.jsonimport {
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:
| Field | Contains |
|---|---|
status | HTTP status, when the API answered |
code | The stable error code, such as missing_scope. See Errors |
message | A readable description |
requestId | The request ID. Include it when you contact support |
requestLogUrl | The Console page for this request, when the API returns one |
docUrl | The documentation link for code |
rateLimitReason | Which limit a 429 hit, such as request_rate or whatsapp |
details | Extra error data from the API |
metadata | Response status, headers and attempt count |
| Class | When |
|---|---|
PolymorfaValidationError | 400, 413 or 422: the request is invalid |
PolymorfaAuthenticationError | 401: the key is missing, invalid, expired or revoked |
PolymorfaPaymentRequiredError | 402: the team cannot pay for the request. The SDK never retries it |
PolymorfaAuthorizationError | 403: the key lacks a permission, or the feature is not enabled for the team |
PolymorfaNotFoundError | 404: the resource does not exist or the key cannot see it |
PolymorfaConflictError | 409: the resource changed, or the keyed request is still running (idempotency_in_progress) or has an unrecorded outcome (idempotency_outcome_unknown) |
PolymorfaRateLimitError | 429: too many requests |
PolymorfaServerError | 5xx: the API failed |
PolymorfaTimeoutError | No response within timeoutMs |
PolymorfaConnectionError | The SDK could not reach the API |
PolymorfaCancelledError | Your signal aborted the request |
PolymorfaConfigurationError | Invalid client options or arguments, thrown before sending |
WebhookSignatureError | A webhook signature did not match |
PolymorfaMediaIntegrityError | Downloaded 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,HEADorOPTIONS, or it has anidempotencyKey. - It failed with a network error, a timeout, or status
408,409,429or5xx.
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.