Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(sdk): expose the error code, retry delay and headers on API errors

Yudhi Armyndharis0bacd844527f
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index d0b622faf..327b60d7f 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -355,19 +355,19 @@ Media bodies share the `SendMediaRequest` shape: `{ chatId, url? | base64?, mime
### Error Handling
-On a non-2xx response the SDK throws a typed `OpenWAApiError` subclass carrying `.status` (HTTP status), `.body` (parsed JSON error envelope, or raw text), and `.errorKind` (the NestJS `error` field, `undefined` when the gateway omits it — which is the norm for a validation rejection in production, where `disableErrorMessages` is on). All error classes extend `OpenWAError` and are exported, so they are `instanceof`-checkable. A timeout throws `OpenWATimeoutError`, which extends `OpenWAError` directly (not `OpenWAApiError`).
-
-| Error class | HTTP status | Meaning |
-| ------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `OpenWAAuthError` | 401 | Missing or invalid API key. |
-| `OpenWAForbiddenError` | 403 | The key's role or scope refuses the call (e.g. an OPERATOR-only route, or a session, IP or chat outside the key's allow-lists). |
-| `OpenWANotFoundError` | 404 | Resource not found. |
-| `OpenWAConflictError` | 409 | Conflict — typically the engine is not ready. |
-| `OpenWARateLimitError` | 429 | Rate limited. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default); its delay is only in the `Retry-After` response header, which the error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's `retryAfterSeconds`, which can be hours. |
-| `OpenWANotImplementedError` | 501 | The active engine does not support this operation. |
-| `OpenWAServiceUnavailableError` | 503 | The engine did not confirm in time. Transient, though a catalog 503 can persist because WhatsApp may never answer that query; 501 is permanent. In a routed deployment a forwarded request answers 503 only when the owner node was never reached; a forward that fails after the request was sent answers 502 or 504, which the owner may already have acted on. |
-| `OpenWAApiError` | any other | Generic non-2xx (the base API error, e.g. `400`; also surfaced for unfollowed 3xx redirects). |
-| `OpenWATimeoutError` | — | The request exceeded the configured timeout. |
+On a non-2xx response the SDK throws a typed `OpenWAApiError` subclass carrying `.status` (HTTP status), `.body` (parsed JSON error envelope, or raw text), and `.errorKind` (the NestJS `error` field, `undefined` when the gateway omits it — which is the norm for a validation rejection in production, where `disableErrorMessages` is on). All error classes extend `OpenWAError` and are exported, so they are `instanceof`-checkable. A timeout throws `OpenWATimeoutError`, which extends `OpenWAError` directly (not `OpenWAApiError`). An API error also carries `.code` (the body's `code`, e.g. `SEND_PACING_LIMITED`), `.retryAfterSeconds` (the body's `retryAfterSeconds`, else the `Retry-After` header) and `.headers` (the response `Headers`).
+
+| Error class | HTTP status | Meaning |
+| ------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `OpenWAAuthError` | 401 | Missing or invalid API key. |
+| `OpenWAForbiddenError` | 403 | The key's role or scope refuses the call (e.g. an OPERATOR-only route, or a session, IP or chat outside the key's allow-lists). |
+| `OpenWANotFoundError` | 404 | Resource not found. |
+| `OpenWAConflictError` | 409 | Conflict — typically the engine is not ready. |
+| `OpenWARateLimitError` | 429 | Rate limited. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default), and `retryAfterSeconds` carries its `Retry-After` header. A 429 whose `code` is `"SEND_PACING_LIMITED"` is not transient: do not retry it before `retryAfterSeconds`, which then comes from the body and can be hours. |
+| `OpenWANotImplementedError` | 501 | The active engine does not support this operation. |
+| `OpenWAServiceUnavailableError` | 503 | The engine did not confirm in time. Transient, though a catalog 503 can persist because WhatsApp may never answer that query; 501 is permanent. In a routed deployment a forwarded request answers 503 only when the owner node was never reached; a forward that fails after the request was sent answers 502 or 504, which the owner may already have acted on. |
+| `OpenWAApiError` | any other | Generic non-2xx (the base API error, e.g. `400`; also surfaced for unfollowed 3xx redirects). |
+| `OpenWATimeoutError` | — | The request exceeded the configured timeout. |
```typescript
import {
@@ -727,19 +727,19 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All
### Error Handling
-Every error inherits from `OpenWAError`. A non-2xx response raises an `OpenWAApiError` (or a more specific subclass picked by status); a timeout raises `OpenWATimeoutError`. The API-error classes carry `.status` (HTTP code), `.body` (parsed JSON or raw text), and `.error_kind` (the NestJS `error` field).
+Every error inherits from `OpenWAError`. A non-2xx response raises an `OpenWAApiError` (or a more specific subclass picked by status); a timeout raises `OpenWATimeoutError`. The API-error classes carry `.status` (HTTP code), `.body` (parsed JSON or raw text), and `.error_kind` (the NestJS `error` field), plus `.code` (the body's `code`), `.retry_after_seconds` (the body's `retryAfterSeconds`, else the `Retry-After` header) and `.headers` (the response headers).
-| Exception | Trigger |
-| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `OpenWAAuthError` | HTTP `401` — missing or invalid API key |
-| `OpenWAForbiddenError` | HTTP `403` — the key's role or scope (session, IP or chat allow-list) refuses the call |
-| `OpenWANotFoundError` | HTTP `404` — resource not found |
-| `OpenWAConflictError` | HTTP `409` — typically engine-not-ready |
-| `OpenWARateLimitError` | HTTP `429` — too many requests. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default); its delay is only in the `Retry-After` response header, which the error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's `retryAfterSeconds`, which can be hours. |
-| `OpenWANotImplementedError` | HTTP `501` — active engine doesn't support the operation |
-| `OpenWAServiceUnavailableError` | HTTP `503` — engine did not confirm in time; transient, though a catalog 503 can persist because WhatsApp may never answer that query. In a routed deployment a forwarded request answers 503 only when the owner node was never reached; a forward that fails after the request was sent answers 502 or 504, which the owner may already have acted on |
-| `OpenWAApiError` | any other non-2xx status (incl. unfollowed `3xx`) |
-| `OpenWATimeoutError` | request exceeded `timeout` (has a `.timeout` attribute) |
+| Exception | Trigger |
+| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `OpenWAAuthError` | HTTP `401` — missing or invalid API key |
+| `OpenWAForbiddenError` | HTTP `403` — the key's role or scope (session, IP or chat allow-list) refuses the call |
+| `OpenWANotFoundError` | HTTP `404` — resource not found |
+| `OpenWAConflictError` | HTTP `409` — typically engine-not-ready |
+| `OpenWARateLimitError` | HTTP `429` — too many requests. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default), and `retry_after_seconds` carries its `Retry-After` header. A 429 whose `code` is `"SEND_PACING_LIMITED"` is not transient: do not retry it before `retry_after_seconds`, which then comes from the body and can be hours. |
+| `OpenWANotImplementedError` | HTTP `501` — active engine doesn't support the operation |
+| `OpenWAServiceUnavailableError` | HTTP `503` — engine did not confirm in time; transient, though a catalog 503 can persist because WhatsApp may never answer that query. In a routed deployment a forwarded request answers 503 only when the owner node was never reached; a forward that fails after the request was sent answers 502 or 504, which the owner may already have acted on |
+| `OpenWAApiError` | any other non-2xx status (incl. unfollowed `3xx`) |
+| `OpenWATimeoutError` | request exceeded `timeout` (has a `.timeout` attribute) |
```python
from openwa import (
@@ -1077,20 +1077,20 @@ All payloads are associative arrays; all listed methods are synchronous and retu
### Error Handling
-All exceptions live in `OpenWA\Exceptions` and descend from `OpenWAException` (which extends PHP's `\Exception`). Any non-2xx response is raised as an `OpenWAApiException`; the static `classify()` factory picks the most specific subclass by status code. An `OpenWAApiException` carries the HTTP status (`getStatus(): int`), the parsed error body (`getBody(): mixed`), and the NestJS `error` kind when present (`getErrorKind(): ?string`).
-
-| Exception | Extends | Trigger |
-| ----------------------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `OpenWAException` | `\Exception` | Base for all SDK errors (also thrown for missing `baseUrl`/`apiKey`). |
-| `OpenWAApiException` | `OpenWAException` | Any non-2xx (including unfollowed 3xx and other 4xx/5xx). |
-| `OpenWAAuthException` | `OpenWAApiException` | `401` — missing/invalid API key. |
-| `OpenWAForbiddenException` | `OpenWAApiException` | `403` — the key's role or scope refuses the call (e.g. operator-only endpoint, or a session, IP or chat outside its allow-lists). |
-| `OpenWANotFoundException` | `OpenWAApiException` | `404` — resource not found. |
-| `OpenWAConflictException` | `OpenWAApiException` | `409` — conflict (e.g. engine not ready). |
-| `OpenWARateLimitException` | `OpenWAApiException` | `429` — rate limited. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default); its delay is only in the `Retry-After` response header, which the error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's `retryAfterSeconds`, which can be hours. |
-| `OpenWANotImplementedException` | `OpenWAApiException` | `501` — active engine does not support the operation. |
-| `OpenWAServiceUnavailableException` | `OpenWAApiException` | `503` — engine did not confirm in time; transient, though a catalog 503 can persist because WhatsApp may never answer that query. In a routed deployment a forwarded request answers 503 only when the owner node was never reached; a forward that fails after the request was sent answers 502 or 504, which the owner may already have acted on. |
-| `OpenWATimeoutException` | `OpenWAException` | Request exceeded the timeout (`getTimeout(): float`). Not an API error — has no status/body. |
+All exceptions live in `OpenWA\Exceptions` and descend from `OpenWAException` (which extends PHP's `\Exception`). Any non-2xx response is raised as an `OpenWAApiException`; the static `classify()` factory picks the most specific subclass by status code. An `OpenWAApiException` carries the HTTP status (`getStatus(): int`), the parsed error body (`getBody(): mixed`), and the NestJS `error` kind when present (`getErrorKind(): ?string`), plus the body's `code` (`getErrorCode(): ?string`), the retry delay in seconds from the body's `retryAfterSeconds` or the `Retry-After` header (`getRetryAfterSeconds(): ?int`) and the response headers (`getHeaders(): array`).
+
+| Exception | Extends | Trigger |
+| ----------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `OpenWAException` | `\Exception` | Base for all SDK errors (also thrown for missing `baseUrl`/`apiKey`). |
+| `OpenWAApiException` | `OpenWAException` | Any non-2xx (including unfollowed 3xx and other 4xx/5xx). |
+| `OpenWAAuthException` | `OpenWAApiException` | `401` — missing/invalid API key. |
+| `OpenWAForbiddenException` | `OpenWAApiException` | `403` — the key's role or scope refuses the call (e.g. operator-only endpoint, or a session, IP or chat outside its allow-lists). |
+| `OpenWANotFoundException` | `OpenWAApiException` | `404` — resource not found. |
+| `OpenWAConflictException` | `OpenWAApiException` | `409` — conflict (e.g. engine not ready). |
+| `OpenWARateLimitException` | `OpenWAApiException` | `429` — rate limited. The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default), and `getRetryAfterSeconds()` carries its `Retry-After` header. A 429 whose `getErrorCode()` is `"SEND_PACING_LIMITED"` is not transient: do not retry it before `getRetryAfterSeconds()`, which then comes from the body and can be hours. |
+| `OpenWANotImplementedException` | `OpenWAApiException` | `501` — active engine does not support the operation. |
+| `OpenWAServiceUnavailableException` | `OpenWAApiException` | `503` — engine did not confirm in time; transient, though a catalog 503 can persist because WhatsApp may never answer that query. In a routed deployment a forwarded request answers 503 only when the owner node was never reached; a forward that fails after the request was sent answers 502 or 504, which the owner may already have acted on. |
+| `OpenWATimeoutException` | `OpenWAException` | Request exceeded the timeout (`getTimeout(): float`). Not an API error — has no status/body. |
```php
<?php
diff --git a/package.json b/package.json
index b1159dc39..00099a13c 100644
--- a/package.json
+++ b/package.json
@@ -42,7 +42,7 @@
"lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-wwebjs-block.spec.js scripts/patch-wwebjs-group-description.spec.js scripts/patch-wwebjs-media-id.spec.js scripts/patch-wwebjs-send-error.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs scripts/check-contract-shapes.spec.mjs scripts/check-sdk-coverage.spec.mjs scripts/cli-entrypoint-guard.spec.mjs",
- "test:docs": "jest src/common/changelog-sections.spec.ts src/common/ci-privilege-gate.spec.ts src/common/docs-ci-jobs.spec.ts src/common/docs-coverage-policy.spec.ts src/common/docs-metrics-list.spec.ts src/common/docs-next-version.spec.ts src/common/openapi/docs-06-contract.spec.ts src/common/test-lane-partition.spec.ts src/config/docs-env-example.spec.ts src/config/openapi-contract.spec.ts src/config/openapi-export-pins.spec.ts src/config/wa-web-version-example-pin.spec.ts src/engine/docs-29-counts.spec.ts src/engine/docs-27-backfill-engine.spec.ts src/engine/engine-inventory-parity.spec.ts src/engine/engine-parity.spec.ts src/engine/inventory-mapping-direction.spec.ts src/engine/adapters/baileys-voice-waveform.spec.ts src/engine/adapters/wwebjs-newsletter-preview.spec.ts src/modules/audit/audit-coverage.spec.ts src/modules/auth/global-route-fence-coverage.spec.ts src/modules/auth/query-session-scope-coverage.spec.ts src/modules/docker/compose-network.spec.ts src/modules/queue/bull-board-mount-coverage.spec.ts src/common/release-gate-parity.spec.ts src/database/migrations/__tests__/migration-drift.spec.ts --testPathIgnorePatterns=/node_modules/",
+ "test:docs": "jest src/common/changelog-sections.spec.ts src/common/ci-privilege-gate.spec.ts src/common/docs-ci-jobs.spec.ts src/common/docs-coverage-policy.spec.ts src/common/docs-metrics-list.spec.ts src/common/docs-next-version.spec.ts src/common/docs-sdk-rate-limit.spec.ts src/common/openapi/docs-06-contract.spec.ts src/common/test-lane-partition.spec.ts src/config/docs-env-example.spec.ts src/config/openapi-contract.spec.ts src/config/openapi-export-pins.spec.ts src/config/wa-web-version-example-pin.spec.ts src/engine/docs-29-counts.spec.ts src/engine/docs-27-backfill-engine.spec.ts src/engine/engine-inventory-parity.spec.ts src/engine/engine-parity.spec.ts src/engine/inventory-mapping-direction.spec.ts src/engine/adapters/baileys-voice-waveform.spec.ts src/engine/adapters/wwebjs-newsletter-preview.spec.ts src/modules/audit/audit-coverage.spec.ts src/modules/auth/global-route-fence-coverage.spec.ts src/modules/auth/query-session-scope-coverage.spec.ts src/modules/docker/compose-network.spec.ts src/modules/queue/bull-board-mount-coverage.spec.ts src/common/release-gate-parity.spec.ts src/database/migrations/__tests__/migration-drift.spec.ts --testPathIgnorePatterns=/node_modules/",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
@@ -157,6 +157,7 @@
"src/common/docs-coverage-policy\\.spec\\.ts$",
"src/common/docs-metrics-list\\.spec\\.ts$",
"src/common/docs-next-version\\.spec\\.ts$",
+ "src/common/docs-sdk-rate-limit\\.spec\\.ts$",
"src/common/openapi/docs-06-contract\\.spec\\.ts$",
"src/common/test-lane-partition\\.spec\\.ts$",
"src/config/docs-env-example\\.spec\\.ts$",
@@ -479,6 +480,7 @@
"src/common/docs-coverage-policy\\.spec\\.ts$",
"src/common/docs-metrics-list\\.spec\\.ts$",
"src/common/docs-next-version\\.spec\\.ts$",
+ "src/common/docs-sdk-rate-limit\\.spec\\.ts$",
"src/common/openapi/docs-06-contract\\.spec\\.ts$",
"src/common/test-lane-partition\\.spec\\.ts$",
"src/config/docs-env-example\\.spec\\.ts$",
diff --git a/sdk/go/README.md b/sdk/go/README.md
index 7440440a5..fbedc68ac 100644
--- a/sdk/go/README.md
+++ b/sdk/go/README.md
@@ -105,13 +105,14 @@ Sentinels: `ErrUnauthorized` (401), `ErrForbidden` (403), `ErrNotFound` (404),
`ErrServiceUnavailable` (503). 503 is transient, but a catalog 503 can persist
because WhatsApp may never answer that query, so bound any retry. A 429 from
the global rate limiter lifts when its window expires (seconds for the
-per-second tier, up to an hour for the hourly tier by default); its delay is
-only in the `Retry-After` response header, which `APIError` does not carry but
-`WithRetry` honors. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not
-transient: do not retry it before the body's `retryAfterSeconds`, which can be
-hours. A timeout surfaces as `*openwa.TimeoutError`. In a routed deployment
-only 503 proves the request was never carried out: a forward that fails after
-the request reached the owner node answers 502 or 504.
+per-second tier, up to an hour for the hourly tier by default);
+`APIError.RetryAfter` carries its `Retry-After` header, which `WithRetry` also
+honors. A 429 whose `APIError.Code` is `"SEND_PACING_LIMITED"` is not transient:
+do not retry it before `RetryAfter`, which then comes from the body and can be
+hours. `APIError.Header` holds the response headers. A timeout surfaces as
+`*openwa.TimeoutError`. In a routed deployment only 503 proves the request was
+never carried out: a forward that fails after the request reached the owner node
+answers 502 or 504.
## Retries
diff --git a/sdk/go/client.go b/sdk/go/client.go
index 6cb7284bc..2220ca308 100644
--- a/sdk/go/client.go
+++ b/sdk/go/client.go
@@ -289,7 +289,7 @@ func (c *Client) doRaw(ctx context.Context, method, path string, query url.Value
// Any non-2xx (including an unfollowed 3xx) is an error.
if resp.StatusCode >= 300 {
- return nil, "", parseAPIError(resp.StatusCode, data, method+" "+path)
+ return nil, "", parseAPIError(resp.StatusCode, data, method+" "+path, resp.Header)
}
return data, resp.Header.Get("Content-Type"), nil
}
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 51fab3efd..b416eb129 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -228,6 +228,53 @@ func TestTypedErrors(t *testing.T) {
}
}
+func TestAPIErrorCodeRetryAfterAndHeader(t *testing.T) {
+ fail := func(status int, body string, header http.Header) *APIError {
+ t.Helper()
+ c := newTestClient(t, &recordTransport{status: status, body: body, header: header})
+ _, err := c.Sessions.List(context.Background(), nil)
+ var apiErr *APIError
+ if !errors.As(err, &apiErr) {
+ t.Fatalf("errors.As *APIError failed for %v", err)
+ }
+ return apiErr
+ }
+
+ throttled := fail(429, `{"statusCode":429,"message":"ThrottlerException: Too Many Requests"}`, http.Header{"Retry-After": {"7"}})
+ if !errors.Is(throttled, ErrRateLimited) || throttled.RetryAfter != 7*time.Second || throttled.Code != "" {
+ t.Fatalf("throttled = %+v", throttled)
+ }
+ if throttled.Header.Get("Retry-After") != "7" {
+ t.Fatalf("Header = %v", throttled.Header)
+ }
+
+ // Send pacing puts its wait in the body; a header must not shorten it.
+ pacing := `{"statusCode":429,"error":"Too Many Requests","message":"Daily send cap reached","code":"SEND_PACING_LIMITED","retryAfterSeconds":34521}`
+ for _, h := range []http.Header{nil, {"Retry-After": {"1"}}} {
+ e := fail(429, pacing, h)
+ if e.Code != "SEND_PACING_LIMITED" || e.RetryAfter != 34521*time.Second {
+ t.Fatalf("pacing with header %v = %+v", h, e)
+ }
+ }
+
+ dated := fail(503, "", http.Header{"Retry-After": {time.Now().Add(2 * time.Second).UTC().Format(http.TimeFormat)}})
+ if dated.RetryAfter <= 0 || dated.RetryAfter > 3*time.Second {
+ t.Fatalf("HTTP-date RetryAfter = %v", dated.RetryAfter)
+ }
+ for _, v := range []string{"soon", "-5"} {
+ if e := fail(503, "", http.Header{"Retry-After": {v}}); e.RetryAfter != 0 {
+ t.Fatalf("Retry-After %q gave %v", v, e.RetryAfter)
+ }
+ }
+
+ if e := fail(502, `{"statusCode":502,"message":"x","code":"SESSION_LOGOUT_INCOMPLETE"}`, nil); e.Code != "SESSION_LOGOUT_INCOMPLETE" {
+ t.Fatalf("Code = %q", e.Code)
+ }
+ if e := fail(500, "oops", nil); e.Code != "" || e.RetryAfter != 0 {
+ t.Fatalf("plain-text error = %+v", e)
+ }
+}
+
func TestArrayMessageError(t *testing.T) {
rt := &recordTransport{
status: 400,
diff --git a/sdk/go/errors.go b/sdk/go/errors.go
index b52b3b449..3f7724041 100644
--- a/sdk/go/errors.go
+++ b/sdk/go/errors.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net/http"
"time"
)
@@ -30,11 +31,10 @@ var (
ErrConflict = errors.New("openwa: conflict")
// ErrRateLimited is returned for a 429 (too many requests). The global rate
// limiter's 429 lifts when its window expires (seconds for the per-second
- // tier, up to an hour for the hourly tier by default); its delay is only in
- // the Retry-After response header, which APIError does not carry but
- // WithRetry honors. A 429 whose Body has code "SEND_PACING_LIMITED" is not
- // transient: do not retry it before the body's retryAfterSeconds, which can
- // be hours.
+ // tier, up to an hour for the hourly tier by default); APIError.RetryAfter
+ // carries its Retry-After header, which WithRetry also honors. A 429 whose
+ // Code is "SEND_PACING_LIMITED" is not transient: do not retry it before
+ // RetryAfter, which then comes from the body and can be hours.
ErrRateLimited = errors.New("openwa: rate limited")
// ErrNotImplemented is returned for a 501 (the active engine does not
// support this operation).
@@ -69,6 +69,15 @@ type APIError struct {
Body any
// Context is the "METHOD /path" that produced the error.
Context string
+ // Code is the body's machine-readable "code" (e.g. "SEND_PACING_LIMITED"),
+ // when the body carries one.
+ Code string
+ // RetryAfter is how long to wait before retrying: the body's
+ // retryAfterSeconds when present, else the Retry-After header (seconds or
+ // an HTTP date). Zero when the response names no delay.
+ RetryAfter time.Duration
+ // Header is the response header.
+ Header http.Header
}
func (e *APIError) Error() string {
@@ -126,7 +135,7 @@ type nestEnvelope struct {
// parseAPIError builds an *APIError from a raw response body, extracting a
// readable message from the NestJS envelope when the body matches that shape.
-func parseAPIError(status int, raw []byte, context string) *APIError {
+func parseAPIError(status int, raw []byte, context string, header http.Header) *APIError {
var body any
var envelope *nestEnvelope
@@ -146,13 +155,24 @@ func parseAPIError(status int, raw []byte, context string) *APIError {
kind = envelope.Error
}
- return &APIError{
+ apiErr := &APIError{
StatusCode: status,
Message: message,
Kind: kind,
Body: body,
Context: context,
+ Header: header,
}
+ fields, _ := body.(map[string]any)
+ apiErr.Code, _ = fields["code"].(string)
+ // The body's retryAfterSeconds wins: send pacing puts its wait (possibly
+ // hours) only there, and a header added by a proxy must not shorten it.
+ if secs, ok := fields["retryAfterSeconds"].(float64); ok && secs >= 0 {
+ apiErr.RetryAfter = time.Duration(secs * float64(time.Second))
+ } else if d, ok := retryAfterHeader(header); ok {
+ apiErr.RetryAfter = d
+ }
+ return apiErr
}
func messageFromEnvelope(envelope *nestEnvelope, body any) string {
diff --git a/sdk/go/retry.go b/sdk/go/retry.go
index 2d8c41b3f..560918d94 100644
--- a/sdk/go/retry.go
+++ b/sdk/go/retry.go
@@ -142,11 +142,16 @@ func parseRetryAfter(resp *http.Response) (time.Duration, bool) {
if resp == nil {
return 0, false
}
- v := resp.Header.Get("Retry-After")
+ return retryAfterHeader(resp.Header)
+}
+
+// retryAfterHeader reads Retry-After as whole seconds or an HTTP date.
+func retryAfterHeader(h http.Header) (time.Duration, bool) {
+ v := h.Get("Retry-After")
if v == "" {
return 0, false
}
- if secs, err := strconv.Atoi(v); err == nil {
+ if secs, err := strconv.Atoi(v); err == nil && secs >= 0 {
return time.Duration(secs) * time.Second, true
}
if t, err := http.ParseTime(v); err == nil {
diff --git a/sdk/java/README.md b/sdk/java/README.md
index e6f7f43e1..d6a27f936 100644
--- a/sdk/java/README.md
+++ b/sdk/java/README.md
@@ -118,7 +118,7 @@ try {
| `OpenWAApiError` | — | Any other non-2xx (carries `.status()`) |
| `OpenWATimeoutError` | — | Request exceeded the configured timeout |
-All extend `OpenWAError` (a `RuntimeException`). 503 is transient, but a catalog 503 can persist because WhatsApp may never answer that query, so bound any retry. A 429 from the global rate limiter clears within seconds; its delay is only in the `Retry-After` response header, which the error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's `retryAfterSeconds`, which can be hours. In a routed deployment only 503 proves the request was never carried out: a forward that fails after the request reached the owner node answers 502 or 504.
+All extend `OpenWAError` (a `RuntimeException`). 503 is transient, but a catalog 503 can persist because WhatsApp may never answer that query, so bound any retry. A 429 from the global rate limiter lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly tier by default), and `retryAfterSeconds()` carries its `Retry-After` header. A 429 whose `code()` is `"SEND_PACING_LIMITED"` is not transient: do not retry it before `retryAfterSeconds()`, which then comes from the body and can be hours. `headers()` returns the response headers. In a routed deployment only 503 proves the request was never carried out: a forward that fails after the request reached the owner node answers 502 or 504.
## Reliability & security
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
index 212f2851d..9233586a7 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
@@ -225,7 +225,7 @@ public final class OpenWAClient {
throw new OpenWAError("Invalid request — " + method + " " + path + ": " + e.getMessage());
}
if (res.status() < 200 || res.status() >= 300) {
- throw OpenWAApiError.fromResponse(res.status(), "", utf8(res.body()), method + " " + path);
+ throw OpenWAApiError.fromResponse(res.status(), "", utf8(res.body()), method + " " + path, res.headers());
}
return res;
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java
index db39207df..77b897192 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java
@@ -3,6 +3,14 @@ package com.rmyndharis.openwa.errors;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
+import java.time.Instant;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeParseException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@@ -20,12 +28,37 @@ public class OpenWAApiError extends OpenWAError {
private final int status;
private final Object body;
private final String errorKind;
+ private final Map<String, List<String>> headers;
+ private final String code;
+ private final Long retryAfterSeconds;
public OpenWAApiError(String message, int status, Object body, String errorKind) {
+ this(message, status, body, errorKind, Map.of());
+ }
+
+ public OpenWAApiError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
super(message);
this.status = status;
this.body = body;
this.errorKind = errorKind;
+ // Case-insensitive like the transport's own map; a null key (the status line from
+ // HttpURLConnection.getHeaderFields()) is not a header and is dropped.
+ TreeMap<String, List<String>> copy = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ if (headers != null) {
+ headers.forEach((k, v) -> {
+ if (k != null) {
+ copy.put(k, v);
+ }
+ });
+ }
+ this.headers = Collections.unmodifiableMap(copy);
+ JsonObject fields = body instanceof JsonObject obj ? obj : new JsonObject();
+ JsonElement codeEl = fields.get("code");
+ this.code = codeEl != null && codeEl.isJsonPrimitive() && codeEl.getAsJsonPrimitive().isString()
+ ? codeEl.getAsString()
+ : null;
+ this.retryAfterSeconds = retryAfter(fields.get("retryAfterSeconds"), header(this.headers, "Retry-After"));
}
/** HTTP status code (e.g. 400, 404, 409, 429, 501). */
@@ -43,6 +76,48 @@ public class OpenWAApiError extends OpenWAError {
return errorKind;
}
+ /** The body's machine-readable {@code code} (e.g. {@code SEND_PACING_LIMITED}), or {@code null}. */
+ public String code() {
+ return code;
+ }
+
+ /**
+ * Seconds to wait before retrying: the body's {@code retryAfterSeconds} when present, else the
+ * {@code Retry-After} header (seconds or an HTTP date), else {@code null}.
+ */
+ public Long retryAfterSeconds() {
+ return retryAfterSeconds;
+ }
+
+ /** The response headers (empty when the error did not come from a response). */
+ public Map<String, List<String>> headers() {
+ return headers;
+ }
+
+ private static String header(Map<String, List<String>> headers, String name) {
+ List<String> values = headers.get(name);
+ return values == null || values.isEmpty() ? null : values.get(0);
+ }
+
+ // The body's retryAfterSeconds wins: send pacing puts its wait (possibly hours) only there, and a
+ // header added by a proxy must not shorten it.
+ private static Long retryAfter(JsonElement fromBody, String header) {
+ if (fromBody != null && fromBody.isJsonPrimitive() && fromBody.getAsJsonPrimitive().isNumber()
+ && fromBody.getAsDouble() >= 0) {
+ return (long) Math.ceil(fromBody.getAsDouble());
+ }
+ String value = header == null ? "" : header.trim();
+ if (value.matches("\\d{1,18}")) {
+ return Long.parseLong(value);
+ }
+ try {
+ Instant at = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant();
+ return Math.max(0L, (long) Math.ceil((at.toEpochMilli() - System.currentTimeMillis()) / 1000.0));
+ } catch (DateTimeParseException e) {
+ return null;
+ }
+ }
+
/**
* Build the most specific error subclass from a non-2xx response. A 3xx
* surfaces as a generic {@link OpenWAApiError} whose message states the
@@ -50,10 +125,16 @@ public class OpenWAApiError extends OpenWAError {
* target).
*/
public static OpenWAApiError fromResponse(int status, String statusText, String rawBody, String context) {
+ return fromResponse(status, statusText, rawBody, context, Map.of());
+ }
+
+ /** As {@link #fromResponse(int, String, String, String)}, keeping the response headers on the error. */
+ public static OpenWAApiError fromResponse(
+ int status, String statusText, String rawBody, String context, Map<String, List<String>> headers) {
if (status >= 300 && status < 400) {
return new OpenWAApiError(
"Unexpected redirect (not followed; the API key is never re-sent to a redirect target) — " + context,
- status, null, null);
+ status, null, null, headers);
}
JsonObject obj = null;
Object parsedBody = rawBody;
@@ -81,7 +162,7 @@ public class OpenWAApiError extends OpenWAError {
String reason = statusText == null || statusText.isBlank() ? "" : " " + statusText;
String tail = messageText.isEmpty() ? "" : ": " + messageText;
String message = "OpenWA API " + status + reason + " — " + context + tail;
- return classify(status, message, parsedBody, errorKind);
+ return classify(status, message, parsedBody, errorKind, headers);
}
private static String describe(JsonElement message, String fallback) {
@@ -100,15 +181,21 @@ public class OpenWAApiError extends OpenWAError {
/** Construct the most specific subclass for a status code. */
public static OpenWAApiError classify(int status, String message, Object body, String errorKind) {
+ return classify(status, message, body, errorKind, Map.of());
+ }
+
+ /** As {@link #classify(int, String, Object, String)}, keeping the response headers on the error. */
+ public static OpenWAApiError classify(
+ int status, String message, Object body, String errorKind, Map<String, List<String>> headers) {
return switch (status) {
- case 401 -> new OpenWAAuthError(message, status, body, errorKind);
- case 403 -> new OpenWAForbiddenError(message, status, body, errorKind);
- case 404 -> new OpenWANotFoundError(message, status, body, errorKind);
- case 409 -> new OpenWAConflictError(message, status, body, errorKind);
- case 429 -> new OpenWARateLimitError(message, status, body, errorKind);
- case 501 -> new OpenWANotImplementedError(message, status, body, errorKind);
- case 503 -> new OpenWAServiceUnavailableError(message, status, body, errorKind);
- default -> new OpenWAApiError(message, status, body, errorKind);
+ case 401 -> new OpenWAAuthError(message, status, body, errorKind, headers);
+ case 403 -> new OpenWAForbiddenError(message, status, body, errorKind, headers);
+ case 404 -> new OpenWANotFoundError(message, status, body, errorKind, headers);
+ case 409 -> new OpenWAConflictError(message, status, body, errorKind, headers);
+ case 429 -> new OpenWARateLimitError(message, status, body, errorKind, headers);
+ case 501 -> new OpenWANotImplementedError(message, status, body, errorKind, headers);
+ case 503 -> new OpenWAServiceUnavailableError(message, status, body, errorKind, headers);
+ default -> new OpenWAApiError(message, status, body, errorKind, headers);
};
}
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAAuthError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAAuthError.java
index 099669904..309a65df5 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAAuthError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAAuthError.java
@@ -1,8 +1,16 @@
package com.rmyndharis.openwa.errors;
+import java.util.List;
+import java.util.Map;
+
/** 401 Unauthorized — missing or invalid API key. */
public class OpenWAAuthError extends OpenWAApiError {
public OpenWAAuthError(String message, int status, Object body, String errorKind) {
super(message, status, body, errorKind);
}
+
+ public OpenWAAuthError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
+ super(message, status, body, errorKind, headers);
+ }
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAConflictError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAConflictError.java
index e229bb468..4fe5d7f5b 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAConflictError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAConflictError.java
@@ -1,8 +1,16 @@
package com.rmyndharis.openwa.errors;
+import java.util.List;
+import java.util.Map;
+
/** 409 Conflict — typically an engine-not-ready condition from the backend. */
public class OpenWAConflictError extends OpenWAApiError {
public OpenWAConflictError(String message, int status, Object body, String errorKind) {
super(message, status, body, errorKind);
}
+
+ public OpenWAConflictError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
+ super(message, status, body, errorKind, headers);
+ }
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAForbiddenError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAForbiddenError.java
index 601870ab1..6fa68673d 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAForbiddenError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAForbiddenError.java
@@ -1,8 +1,16 @@
package com.rmyndharis.openwa.errors;
+import java.util.List;
+import java.util.Map;
+
/** 403 Forbidden — the API key's role is insufficient for this endpoint. */
public class OpenWAForbiddenError extends OpenWAApiError {
public OpenWAForbiddenError(String message, int status, Object body, String errorKind) {
super(message, status, body, errorKind);
}
+
+ public OpenWAForbiddenError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
+ super(message, status, body, errorKind, headers);
+ }
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotFoundError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotFoundError.java
index 3ca3f155b..03d28df18 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotFoundError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotFoundError.java
@@ -1,8 +1,16 @@
package com.rmyndharis.openwa.errors;
+import java.util.List;
+import java.util.Map;
+
/** 404 Not Found. */
public class OpenWANotFoundError extends OpenWAApiError {
public OpenWANotFoundError(String message, int status, Object body, String errorKind) {
super(message, status, body, errorKind);
}
+
+ public OpenWANotFoundError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
+ super(message, status, body, errorKind, headers);
+ }
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotImplementedError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotImplementedError.java
index c03c0f456..7d06355d9 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotImplementedError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWANotImplementedError.java
@@ -1,8 +1,16 @@
package com.rmyndharis.openwa.errors;
+import java.util.List;
+import java.util.Map;
+
/** 501 Not Implemented — the active engine does not support this operation. */
public class OpenWANotImplementedError extends OpenWAApiError {
public OpenWANotImplementedError(String message, int status, Object body, String errorKind) {
super(message, status, body, errorKind);
}
+
+ public OpenWANotImplementedError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
+ super(message, status, body, errorKind, headers);
+ }
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWARateLimitError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWARateLimitError.java
index 72c44346b..d295a554b 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWARateLimitError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWARateLimitError.java
@@ -1,16 +1,24 @@
package com.rmyndharis.openwa.errors;
+import java.util.List;
+import java.util.Map;
+
/**
* 429 Too Many Requests — rate limited.
*
* <p>The global rate limiter's 429 lifts when its window expires (seconds for the per-second tier,
- * up to an hour for the hourly tier by default); its delay is only in the {@code Retry-After}
- * response header, which this error does not carry. A 429 whose body has {@code code:
- * "SEND_PACING_LIMITED"} is not transient: do not retry it before the body's {@code
- * retryAfterSeconds}, which can be hours.
+ * up to an hour for the hourly tier by default), and {@link #retryAfterSeconds()} carries its
+ * {@code Retry-After} header. A 429 whose {@link #code()} is {@code "SEND_PACING_LIMITED"} is not
+ * transient: do not retry it before {@link #retryAfterSeconds()}, which then comes from the body and
+ * can be hours.
*/
public class OpenWARateLimitError extends OpenWAApiError {
public OpenWARateLimitError(String message, int status, Object body, String errorKind) {
super(message, status, body, errorKind);
}
+
+ public OpenWARateLimitError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
+ super(message, status, body, errorKind, headers);
+ }
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAServiceUnavailableError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAServiceUnavailableError.java
index b1c6cfded..072210023 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAServiceUnavailableError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAServiceUnavailableError.java
@@ -1,5 +1,8 @@
package com.rmyndharis.openwa.errors;
+import java.util.List;
+import java.util.Map;
+
/**
* 503 Service Unavailable — a transport failure, not a refusal.
*
@@ -16,4 +19,9 @@ public class OpenWAServiceUnavailableError extends OpenWAApiError {
public OpenWAServiceUnavailableError(String message, int status, Object body, String errorKind) {
super(message, status, body, errorKind);
}
+
+ public OpenWAServiceUnavailableError(
+ String message, int status, Object body, String errorKind, Map<String, List<String>> headers) {
+ super(message, status, body, errorKind, headers);
+ }
}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
index 4a6e89821..4202144f8 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
@@ -6,13 +6,18 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import com.rmyndharis.openwa.errors.OpenWAApiError;
import com.rmyndharis.openwa.errors.OpenWAError;
import com.rmyndharis.openwa.errors.OpenWANotFoundError;
+import com.rmyndharis.openwa.errors.OpenWARateLimitError;
import com.rmyndharis.openwa.http.BinaryResponse;
import com.rmyndharis.openwa.http.HttpMethod;
import com.rmyndharis.openwa.model.SuccessResult;
import com.rmyndharis.openwa.support.MockTransport;
import java.nio.charset.StandardCharsets;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
@@ -39,6 +44,61 @@ class ClientTest {
assertNull(tx.lastRequest());
}
+ @Test
+ void apiErrorCarriesCodeRetryAfterAndHeaders() {
+ tx.respondRaw(429, "{\"statusCode\":429,\"message\":\"ThrottlerException: Too Many Requests\"}"
+ .getBytes(StandardCharsets.UTF_8), Map.of("retry-after", List.of("7")));
+ OpenWARateLimitError throttled = assertThrows(OpenWARateLimitError.class,
+ () -> client.requestVoid(HttpMethod.GET, "/api/sessions", null, null));
+ assertEquals(7L, throttled.retryAfterSeconds());
+ assertNull(throttled.code());
+ assertEquals(List.of("7"), throttled.headers().get("retry-after"));
+
+ // Header lookup ignores case, as it does on the java.net.http transport's own map.
+ tx.respondRaw(429, new byte[0], Map.of("Retry-After", List.of("7")));
+ OpenWAApiError cased = assertThrows(OpenWAApiError.class,
+ () -> client.requestVoid(HttpMethod.GET, "/api/sessions", null, null));
+ assertEquals(List.of("7"), cased.headers().get("retry-after"));
+ assertEquals(List.of("7"), cased.headers().get("RETRY-AFTER"));
+ // A transport built on HttpURLConnection reports the status line under a null key.
+ Map<String, List<String>> withStatusLine = new java.util.HashMap<>();
+ withStatusLine.put(null, List.of("HTTP/1.1 429"));
+ withStatusLine.put("Retry-After", List.of("3"));
+ assertEquals(3L, new OpenWARateLimitError("m", 429, null, null, withStatusLine).retryAfterSeconds());
+
+ // Send pacing puts its wait in the body; a header must not shorten it.
+ byte[] pacing = ("{\"statusCode\":429,\"error\":\"Too Many Requests\",\"message\":\"Daily send cap reached\","
+ + "\"code\":\"SEND_PACING_LIMITED\",\"retryAfterSeconds\":34521}").getBytes(StandardCharsets.UTF_8);
+ for (Map<String, List<String>> headers : List.of(Map.<String, List<String>>of(), Map.of("Retry-After", List.of("1")))) {
+ tx.respondRaw(429, pacing, headers);
+ OpenWAApiError e = assertThrows(OpenWAApiError.class,
+ () -> client.requestVoid(HttpMethod.GET, "/api/sessions", null, null));
+ assertEquals("SEND_PACING_LIMITED", e.code());
+ assertEquals(34521L, e.retryAfterSeconds());
+ }
+
+ String date = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(2));
+ tx.respondRaw(503, new byte[0], Map.of("Retry-After", List.of(date)));
+ long dated = assertThrows(OpenWAApiError.class,
+ () -> client.requestVoid(HttpMethod.GET, "/api/sessions", null, null)).retryAfterSeconds();
+ assertTrue(dated >= 0 && dated <= 3, "HTTP-date Retry-After gave " + dated);
+ tx.respondRaw(503, new byte[0], Map.of("Retry-After", List.of("soon")));
+ assertNull(assertThrows(OpenWAApiError.class,
+ () -> client.requestVoid(HttpMethod.GET, "/api/sessions", null, null)).retryAfterSeconds());
+
+ tx.respond(502, "{\"statusCode\":502,\"message\":\"x\",\"code\":\"SESSION_LOGOUT_INCOMPLETE\"}");
+ assertEquals("SESSION_LOGOUT_INCOMPLETE", assertThrows(OpenWAApiError.class,
+ () -> client.requestVoid(HttpMethod.GET, "/api/sessions", null, null)).code());
+ tx.respondRaw(500, "oops".getBytes(StandardCharsets.UTF_8), Map.of());
+ OpenWAApiError plain = assertThrows(OpenWAApiError.class,
+ () -> client.requestVoid(HttpMethod.GET, "/api/sessions", null, null));
+ assertNull(plain.code());
+ assertNull(plain.retryAfterSeconds());
+
+ // The four-argument constructor still works and has no headers.
+ assertTrue(new OpenWARateLimitError("m", 429, null, null).headers().isEmpty());
+ }
+
@Test
void requestSendsAuthHeaderAndParsesBody() {
tx.respond(200, "{\"success\":true}");
diff --git a/sdk/javascript/README.md b/sdk/javascript/README.md
index 9833aea76..52a3d3b62 100644
--- a/sdk/javascript/README.md
+++ b/sdk/javascript/README.md
@@ -51,12 +51,12 @@ retry — wrap calls with your own backoff if needed. 503 is transient, but a
catalog 503 can persist because WhatsApp may never answer that query, so bound
any retry. A 429 from the global rate limiter lifts when its window expires
(seconds for the per-second tier, up to an hour for the hourly tier by
-default); its delay is only in the `Retry-After` response header, which the
-error does not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is
-not transient: do not retry it before the body's `retryAfterSeconds`, which
-can be hours. In a routed deployment only 503 proves the request was never
-carried out: a forward that fails after the request reached the owner node
-answers 502 or 504.
+default), and `.retryAfterSeconds` carries its `Retry-After` header. A 429 whose
+`.code` is `"SEND_PACING_LIMITED"` is not transient: do not retry it before
+`.retryAfterSeconds`, which then comes from the body and can be hours. Every API
+error also exposes the response `.headers`. In a routed deployment only 503
+proves the request was never carried out: a forward that fails after the request
+reached the owner node answers 502 or 504.
## Releasing
diff --git a/sdk/javascript/src/errors.ts b/sdk/javascript/src/errors.ts
index b5b4eb09b..47086d34d 100644
--- a/sdk/javascript/src/errors.ts
+++ b/sdk/javascript/src/errors.ts
@@ -31,13 +31,26 @@ export class OpenWAApiError extends OpenWAError {
readonly body: unknown;
/** Value of the `error` field in the NestJS error envelope, if present. */
readonly errorKind?: string;
+ /** The body's machine-readable `code` (e.g. `SEND_PACING_LIMITED`), if the body carries one. */
+ readonly code?: string;
+ /**
+ * Seconds to wait before retrying: the body's `retryAfterSeconds` when present, else the
+ * `Retry-After` response header (seconds or an HTTP date). Undefined when neither is sent.
+ */
+ readonly retryAfterSeconds?: number;
+ /** The response headers, when the error came from a response. */
+ readonly headers?: Headers;
- constructor(message: string, status: number, body: unknown, errorKind?: string) {
+ constructor(message: string, status: number, body: unknown, errorKind?: string, headers?: Headers) {
super(message);
this.name = 'OpenWAApiError';
this.status = status;
this.body = body;
this.errorKind = errorKind;
+ this.headers = headers;
+ const fields = typeof body === 'object' && body !== null ? (body as Record<string, unknown>) : {};
+ if (typeof fields.code === 'string') this.code = fields.code;
+ this.retryAfterSeconds = retryAfterSeconds(fields.retryAfterSeconds, headers?.get('retry-after'));
}
/** Build an {@link OpenWAApiError} from a fetch Response, awaiting its body. */
@@ -64,7 +77,7 @@ export class OpenWAApiError extends OpenWAError {
const env = isNestEnvelope(body) ? body : undefined;
const messageText = describeMessage(env?.message ?? body ?? res.statusText);
const message = `OpenWA API ${res.status} ${res.statusText} — ${context}: ${messageText}`;
- return new OpenWAApiError(message, res.status, body, env?.error);
+ return new OpenWAApiError(message, res.status, body, env?.error, res.headers);
}
}
@@ -77,11 +90,11 @@ export class OpenWANotFoundError extends OpenWAApiError {}
/** 409 Conflict — typically an {@link EngineNotReadyError} from the backend. */
export class OpenWAConflictError extends OpenWAApiError {}
/**
- * 429 Too Many Requests — rate limited. The global rate limiter's 429 lifts when its window
- * expires (seconds for the per-second tier, up to an hour for the hourly tier by default); its
- * delay is only in the `Retry-After` response header, which this error does not carry. A 429 whose
- * `body` has `code: 'SEND_PACING_LIMITED'` is not transient: do not retry it before
- * `body.retryAfterSeconds`, which can be hours.
+ * 429 Too Many Requests: rate limited. The global rate limiter's 429 lifts when its window
+ * expires (seconds for the per-second tier, up to an hour for the hourly tier by default), and
+ * `retryAfterSeconds` carries its `Retry-After` header. A 429 with `code: 'SEND_PACING_LIMITED'` is
+ * not transient: do not retry it before `retryAfterSeconds`, which then comes from the body and can
+ * be hours.
*/
export class OpenWARateLimitError extends OpenWAApiError {}
/** 501 Not Implemented — the active engine does not support this operation. */
@@ -114,27 +127,49 @@ export class OpenWATimeoutError extends OpenWAError {
* Construct the most specific {@link OpenWAApiError} subclass for a status code.
* Falls back to the generic {@link OpenWAApiError} for unmapped statuses.
*/
-export function classifyApiError(status: number, message: string, body: unknown, errorKind?: string): OpenWAApiError {
+export function classifyApiError(
+ status: number,
+ message: string,
+ body: unknown,
+ errorKind?: string,
+ headers?: Headers,
+): OpenWAApiError {
switch (status) {
case 401:
- return new OpenWAAuthError(message, status, body, errorKind);
+ return new OpenWAAuthError(message, status, body, errorKind, headers);
case 403:
- return new OpenWAForbiddenError(message, status, body, errorKind);
+ return new OpenWAForbiddenError(message, status, body, errorKind, headers);
case 404:
- return new OpenWANotFoundError(message, status, body, errorKind);
+ return new OpenWANotFoundError(message, status, body, errorKind, headers);
case 409:
- return new OpenWAConflictError(message, status, body, errorKind);
+ return new OpenWAConflictError(message, status, body, errorKind, headers);
case 429:
- return new OpenWARateLimitError(message, status, body, errorKind);
+ return new OpenWARateLimitError(message, status, body, errorKind, headers);
case 501:
- return new OpenWANotImplementedError(message, status, body, errorKind);
+ return new OpenWANotImplementedError(message, status, body, errorKind, headers);
case 503:
- return new OpenWAServiceUnavailableError(message, status, body, errorKind);
+ return new OpenWAServiceUnavailableError(message, status, body, errorKind, headers);
default:
- return new OpenWAApiError(message, status, body, errorKind);
+ return new OpenWAApiError(message, status, body, errorKind, headers);
}
}
+/**
+ * The body's `retryAfterSeconds` wins: send pacing puts its wait (possibly hours) only there, and a
+ * header added by a proxy must not shorten it. Otherwise read `Retry-After` as seconds or an HTTP
+ * date, clamped at 0.
+ */
+function retryAfterSeconds(fromBody: unknown, header: string | null | undefined): number | undefined {
+ if (typeof fromBody === 'number' && Number.isFinite(fromBody) && fromBody >= 0) return Math.ceil(fromBody);
+ const value = header?.trim();
+ if (!value) return undefined;
+ if (/^\d+$/.test(value)) return Number(value);
+ // Date.parse also accepts '-5' or '1.5' as a past date, which would read as "retry now".
+ if (!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)) return undefined;
+ const at = Date.parse(value);
+ return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - Date.now()) / 1000));
+}
+
/**
* Narrow the NestJS error envelope shape: `{ statusCode, message, error }`.
*
diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.ts
index dcb8d0aae..fbf2d3842 100644
--- a/sdk/javascript/src/http.ts
+++ b/sdk/javascript/src/http.ts
@@ -209,7 +209,7 @@ async function send<T>(
if (!res.ok) {
const context = `${options.method} ${options.path}`;
const apiError = await OpenWAApiError.fromResponse(res, context);
- throw classifyApiError(apiError.status, apiError.message, apiError.body, apiError.errorKind);
+ throw classifyApiError(apiError.status, apiError.message, apiError.body, apiError.errorKind, apiError.headers);
}
return await consume(res);
diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.ts
index 124bc2b39..e8d433bf4 100644
--- a/sdk/javascript/test/client.test.ts
+++ b/sdk/javascript/test/client.test.ts
@@ -12,7 +12,7 @@ import {
OpenWATimeoutError,
} from '../src';
import type { FetchLike } from '../src';
-import { MockTransport } from './helpers';
+import { MockTransport, type MockResponseSpec } from './helpers';
function client(transport: MockTransport): OpenWAClient {
return new OpenWAClient({
@@ -253,6 +253,54 @@ describe('OpenWAClient', () => {
}
});
+ it('exposes the body code, the retry delay and the response headers on an API error', async () => {
+ const fail = async (spec: MockResponseSpec): Promise<OpenWAApiError> =>
+ (await client(new MockTransport().passthrough(spec))
+ .sessions.list()
+ .catch((e: unknown) => e)) as OpenWAApiError;
+
+ const throttled = await fail({
+ status: 429,
+ headers: { 'Retry-After': '7' },
+ body: { statusCode: 429, message: 'ThrottlerException: Too Many Requests' },
+ });
+ expect(throttled).toBeInstanceOf(OpenWARateLimitError);
+ expect(throttled.retryAfterSeconds).toBe(7);
+ expect(throttled.code).toBeUndefined();
+ expect(throttled.headers?.get('retry-after')).toBe('7');
+
+ // Send pacing puts its wait in the body; a header must not shorten it.
+ const pacing = {
+ statusCode: 429,
+ error: 'Too Many Requests',
+ message: 'Daily send cap reached',
+ code: 'SEND_PACING_LIMITED',
+ retryAfterSeconds: 34521,
+ };
+ for (const headers of [undefined, { 'Retry-After': '1' }]) {
+ const err = await fail({ status: 429, headers, body: pacing });
+ expect(err.code).toBe('SEND_PACING_LIMITED');
+ expect(err.retryAfterSeconds).toBe(34521);
+ }
+
+ const dated = await fail({ status: 503, headers: { 'Retry-After': new Date(Date.now() + 2000).toUTCString() } });
+ expect(dated.retryAfterSeconds).toBeGreaterThanOrEqual(0);
+ expect(dated.retryAfterSeconds).toBeLessThanOrEqual(3);
+ // Only whole seconds or an HTTP date count; Date.parse would read '-5' or '1.5' as a past date.
+ for (const bad of ['soon', '-5', '1.5', 'Tue 5']) {
+ expect((await fail({ status: 503, headers: { 'Retry-After': bad } })).retryAfterSeconds).toBeUndefined();
+ }
+
+ const logout = await fail({
+ status: 502,
+ body: { statusCode: 502, message: 'x', code: 'SESSION_LOGOUT_INCOMPLETE' },
+ });
+ expect(logout.code).toBe('SESSION_LOGOUT_INCOMPLETE');
+ const plain = await fail({ status: 500, text: 'oops', contentType: 'text/plain' });
+ expect(plain.code).toBeUndefined();
+ expect(plain.retryAfterSeconds).toBeUndefined();
+ });
+
it('falls back to the generic OpenWAApiError (with .status) for an unmapped status', async () => {
const t = new MockTransport().on('GET', '/api/sessions', {
status: 418,
diff --git a/sdk/javascript/test/helpers.ts b/sdk/javascript/test/helpers.ts
index 02d6f07ea..275b5dbc7 100644
--- a/sdk/javascript/test/helpers.ts
+++ b/sdk/javascript/test/helpers.ts
@@ -18,6 +18,8 @@ export interface MockResponseSpec {
text?: string;
/** Overrides the default `application/json` response content type. */
contentType?: string;
+ /** Extra response headers. */
+ headers?: Record<string, string>;
}
/** A scripted mock transport. Throws if a call doesn't match a route. */
@@ -99,7 +101,10 @@ export class MockTransport {
const responseBody: BodyInit | null = noBody
? null
: (spec.text ?? (spec.body === undefined ? '' : JSON.stringify(spec.body)));
- const resHeaders: Record<string, string> = noBody ? {} : { 'content-type': spec.contentType ?? 'application/json' };
+ const resHeaders: Record<string, string> = {
+ ...(noBody ? {} : { 'content-type': spec.contentType ?? 'application/json' }),
+ ...spec.headers,
+ };
return new Response(responseBody, { status, headers: resHeaders });
}) as FetchLike;
}
diff --git a/sdk/php/README.md b/sdk/php/README.md
index c4c2a208f..7bcfbad8f 100644
--- a/sdk/php/README.md
+++ b/sdk/php/README.md
@@ -60,11 +60,12 @@ A non-2xx response throws a typed `OpenWA\Exceptions\OpenWAApiException` subclas
exposing `getStatus()` and the parsed `getBody()`. A timeout throws `OpenWATimeoutException`.
503 is transient, but a catalog 503 can persist because WhatsApp may never answer that query,
so bound any retry. A 429 from the global rate limiter lifts when its window expires (seconds for
-the per-second tier, up to an hour for the hourly tier by default); its delay is only in the
-`Retry-After` response header, which the error does not carry. A 429 whose body has
-`code: "SEND_PACING_LIMITED"` is not transient: do not retry it before the body's
-`retryAfterSeconds`, which can be hours. In a routed deployment only 503 proves the request was
-never carried out: a forward that fails after the request reached the owner node answers 502 or 504.
+the per-second tier, up to an hour for the hourly tier by default), and `getRetryAfterSeconds()`
+carries its `Retry-After` header. A 429 whose `getErrorCode()` is `"SEND_PACING_LIMITED"` is not
+transient: do not retry it before `getRetryAfterSeconds()`, which then comes from the body and can
+be hours. `getHeaders()` returns the response headers. In a routed deployment only 503 proves the
+request was never carried out: a forward that fails after the request reached the owner node answers
+502 or 504.
```php
use OpenWA\Exceptions\OpenWANotFoundException;
diff --git a/sdk/php/src/Exceptions/OpenWAApiException.php b/sdk/php/src/Exceptions/OpenWAApiException.php
index c19f11e36..ab4fb234d 100644
--- a/sdk/php/src/Exceptions/OpenWAApiException.php
+++ b/sdk/php/src/Exceptions/OpenWAApiException.php
@@ -7,8 +7,9 @@ namespace OpenWA\Exceptions;
/**
* Raised when the API responds with a non-2xx status.
*
- * Carries the HTTP status code and the parsed error body. Use the named
- * subclass for common statuses, or branch on getStatus().
+ * Carries the HTTP status code, the parsed error body, the body's error code,
+ * the retry delay and the response headers. Use the named subclass for common
+ * statuses, or branch on getStatus().
*/
class OpenWAApiException extends OpenWAException
{
@@ -16,16 +17,31 @@ class OpenWAApiException extends OpenWAException
/** @var mixed */
private $body;
private ?string $errorKind;
+ /** @var array<string, string[]> */
+ private array $headers;
+ private ?string $errorCode;
+ private ?int $retryAfterSeconds;
/**
* @param mixed $body
+ * @param array<string, string[]|string> $headers
*/
- public function __construct(string $message, int $status, $body = null, ?string $errorKind = null)
- {
+ public function __construct(
+ string $message,
+ int $status,
+ $body = null,
+ ?string $errorKind = null,
+ array $headers = []
+ ) {
parent::__construct($message);
$this->status = $status;
$this->body = $body;
$this->errorKind = $errorKind;
+ $this->headers = array_map(fn ($v) => (array) $v, $headers);
+ $fields = is_array($body) ? $body : [];
+ $this->errorCode = is_string($fields['code'] ?? null) ? $fields['code'] : null;
+ $retryHeader = array_change_key_case($this->headers)['retry-after'][0] ?? null;
+ $this->retryAfterSeconds = self::retryAfter($fields['retryAfterSeconds'] ?? null, $retryHeader);
}
public function getStatus(): int
@@ -44,22 +60,79 @@ class OpenWAApiException extends OpenWAException
return $this->errorKind;
}
+ /**
+ * The body's machine-readable `code` (e.g. SEND_PACING_LIMITED), if any.
+ * Exception::getCode() is final and returns an int, hence the name.
+ */
+ public function getErrorCode(): ?string
+ {
+ return $this->errorCode;
+ }
+
+ /**
+ * Seconds to wait before retrying: the body's `retryAfterSeconds` when
+ * present, else the Retry-After header (seconds or an HTTP date), else null.
+ */
+ public function getRetryAfterSeconds(): ?int
+ {
+ return $this->retryAfterSeconds;
+ }
+
+ /**
+ * The response headers (empty when the exception did not come from a response).
+ *
+ * @return array<string, string[]>
+ */
+ public function getHeaders(): array
+ {
+ return $this->headers;
+ }
+
+ /**
+ * The body's retryAfterSeconds wins: send pacing puts its wait (possibly
+ * hours) only there, and a header added by a proxy must not shorten it.
+ *
+ * @param mixed $fromBody
+ */
+ private static function retryAfter($fromBody, ?string $header): ?int
+ {
+ if ((is_int($fromBody) || is_float($fromBody)) && $fromBody >= 0) {
+ return (int) ceil($fromBody);
+ }
+ $value = trim((string) $header);
+ if ($value === '') {
+ return null;
+ }
+ // Not ctype_digit(): ext-ctype is optional and this SDK does not require it.
+ if (preg_match('/^\d+$/D', $value) === 1) {
+ return (int) $value;
+ }
+ $at = \DateTimeImmutable::createFromFormat('D, d M Y H:i:s \G\M\T', $value, new \DateTimeZone('UTC'));
+ return $at === false ? null : max(0, $at->getTimestamp() - time());
+ }
+
/**
* Build the most specific OpenWAApiException subclass for a status code.
*
* @param mixed $body
+ * @param array<string, string[]|string> $headers
*/
- public static function classify(int $status, string $message, $body, ?string $errorKind): OpenWAApiException
- {
+ public static function classify(
+ int $status,
+ string $message,
+ $body,
+ ?string $errorKind,
+ array $headers = []
+ ): OpenWAApiException {
return match ($status) {
- 401 => new OpenWAAuthException($message, $status, $body, $errorKind),
- 403 => new OpenWAForbiddenException($message, $status, $body, $errorKind),
- 404 => new OpenWANotFoundException($message, $status, $body, $errorKind),
- 409 => new OpenWAConflictException($message, $status, $body, $errorKind),
- 429 => new OpenWARateLimitException($message, $status, $body, $errorKind),
- 501 => new OpenWANotImplementedException($message, $status, $body, $errorKind),
- 503 => new OpenWAServiceUnavailableException($message, $status, $body, $errorKind),
- default => new OpenWAApiException($message, $status, $body, $errorKind),
+ 401 => new OpenWAAuthException($message, $status, $body, $errorKind, $headers),
+ 403 => new OpenWAForbiddenException($message, $status, $body, $errorKind, $headers),
+ 404 => new OpenWANotFoundException($message, $status, $body, $errorKind, $headers),
+ 409 => new OpenWAConflictException($message, $status, $body, $errorKind, $headers),
+ 429 => new OpenWARateLimitException($message, $status, $body, $errorKind, $headers),
+ 501 => new OpenWANotImplementedException($message, $status, $body, $errorKind, $headers),
+ 503 => new OpenWAServiceUnavailableException($message, $status, $body, $errorKind, $headers),
+ default => new OpenWAApiException($message, $status, $body, $errorKind, $headers),
};
}
}
diff --git a/sdk/php/src/Exceptions/OpenWARateLimitException.php b/sdk/php/src/Exceptions/OpenWARateLimitException.php
index c0e0207ab..f1150da55 100644
--- a/sdk/php/src/Exceptions/OpenWARateLimitException.php
+++ b/sdk/php/src/Exceptions/OpenWARateLimitException.php
@@ -8,10 +8,10 @@ namespace OpenWA\Exceptions;
* 429 Too Many Requests — rate limited.
*
* The global rate limiter's 429 lifts when its window expires (seconds for the
- * per-second tier, up to an hour for the hourly tier by default); its delay is
- * only in the Retry-After response header, which this exception does not carry.
- * A 429 whose body has code "SEND_PACING_LIMITED" is not transient: do not retry
- * it before the body's retryAfterSeconds, which can be hours.
+ * per-second tier, up to an hour for the hourly tier by default), and
+ * getRetryAfterSeconds() carries its Retry-After header. A 429 whose
+ * getErrorCode() is "SEND_PACING_LIMITED" is not transient: do not retry it
+ * before getRetryAfterSeconds(), which then comes from the body and can be hours.
*/
class OpenWARateLimitException extends OpenWAApiException
{
diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.php
index bbdde33bb..a22330305 100644
--- a/sdk/php/src/Http/HttpExecutor.php
+++ b/sdk/php/src/Http/HttpExecutor.php
@@ -216,6 +216,12 @@ class HttpExecutor
$reason = $response->getReasonPhrase();
$message = "OpenWA API {$status} {$reason} — {$method} {$path}: {$messageText}";
- return OpenWAApiException::classify($status, $message, $data, $envelope['error'] ?? null);
+ return OpenWAApiException::classify(
+ $status,
+ $message,
+ $data,
+ $envelope['error'] ?? null,
+ $response->getHeaders(),
+ );
}
}
diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.php
index d82be2a45..cfe519817 100644
--- a/sdk/php/tests/ClientTest.php
+++ b/sdk/php/tests/ClientTest.php
@@ -7,6 +7,7 @@ namespace OpenWA\Tests;
use OpenWA\Exceptions\OpenWAApiException;
use OpenWA\Exceptions\OpenWAAuthException;
use OpenWA\Exceptions\OpenWANotFoundException;
+use OpenWA\Exceptions\OpenWARateLimitException;
use OpenWA\Exceptions\OpenWAServiceUnavailableException;
use OpenWA\Exceptions\OpenWATimeoutException;
use PHPUnit\Framework\TestCase;
@@ -235,6 +236,76 @@ class ClientTest extends TestCase
}
}
+ public function testErrorCarriesCodeRetryAfterAndHeaders(): void
+ {
+ $fail = function (int $status, $body = null, array $headers = [], ?string $raw = null): OpenWAApiException {
+ $backend = new MockBackend();
+ $raw === null ? $backend->on($status, $body, $headers) : $backend->onRaw($status, $raw, $headers);
+ try {
+ $backend->makeClient()->sessions->list();
+ } catch (OpenWAApiException $e) {
+ return $e;
+ }
+ $this->fail('Expected exception');
+ };
+
+ $throttled = $fail(429, ['statusCode' => 429, 'message' => 'ThrottlerException: Too Many Requests'], [
+ 'retry-after' => '7',
+ ]);
+ $this->assertInstanceOf(OpenWARateLimitException::class, $throttled);
+ $this->assertSame(7, $throttled->getRetryAfterSeconds());
+ $this->assertNull($throttled->getErrorCode());
+ $this->assertSame(['7'], $throttled->getHeaders()['retry-after']);
+ $this->assertSame(0, $throttled->getCode());
+
+ // Send pacing puts its wait in the body; a header must not shorten it.
+ $pacing = [
+ 'statusCode' => 429,
+ 'error' => 'Too Many Requests',
+ 'message' => 'Daily send cap reached',
+ 'code' => 'SEND_PACING_LIMITED',
+ 'retryAfterSeconds' => 34521,
+ ];
+ foreach ([[], ['Retry-After' => '1']] as $headers) {
+ $e = $fail(429, $pacing, $headers);
+ $this->assertSame('SEND_PACING_LIMITED', $e->getErrorCode());
+ $this->assertSame(34521, $e->getRetryAfterSeconds());
+ }
+
+ $dated = $fail(503, null, ['Retry-After' => gmdate('D, d M Y H:i:s', time() + 2) . ' GMT'])
+ ->getRetryAfterSeconds();
+ $this->assertTrue($dated !== null && $dated >= 0 && $dated <= 3, "HTTP-date Retry-After gave {$dated}");
+ $this->assertNull($fail(503, null, ['Retry-After' => 'soon'])->getRetryAfterSeconds());
+
+ $logout = $fail(502, ['statusCode' => 502, 'message' => 'x', 'code' => 'SESSION_LOGOUT_INCOMPLETE']);
+ $this->assertSame('SESSION_LOGOUT_INCOMPLETE', $logout->getErrorCode());
+ $plain = $fail(500, null, ['Content-Type' => 'text/plain'], 'oops');
+ $this->assertNull($plain->getErrorCode());
+ $this->assertNull($plain->getRetryAfterSeconds());
+
+ // The four-argument constructor still works and has no headers.
+ $this->assertSame([], (new OpenWARateLimitException('m', 429))->getHeaders());
+ }
+
+ public function testRetryAfterParsesWithoutTheCtypeExtension(): void
+ {
+ // The SDK does not require ext-ctype, so a build without it must still
+ // classify a Retry-After response. Run the check in a child process
+ // with the ctype functions disabled.
+ $autoload = var_export(dirname(__DIR__) . '/vendor/autoload.php', true);
+ $script = "require {$autoload};"
+ . "\$e = \\OpenWA\\Exceptions\\OpenWAApiException::classify(429, 'm', null, null, ['Retry-After' => '7']);"
+ . "echo get_class(\$e), ' ', var_export(\$e->getRetryAfterSeconds(), true);";
+ $ctype = 'ctype_alnum,ctype_alpha,ctype_cntrl,ctype_digit,ctype_graph,'
+ . 'ctype_lower,ctype_print,ctype_punct,ctype_space,ctype_upper,ctype_xdigit';
+ $command = escapeshellarg(PHP_BINARY) . ' -d ' . escapeshellarg("disable_functions={$ctype}")
+ . ' -r ' . escapeshellarg($script) . ' 2>&1';
+ exec($command, $output, $exitCode);
+
+ $this->assertSame(0, $exitCode, implode("\n", $output));
+ $this->assertSame(OpenWARateLimitException::class . ' 7', implode("\n", $output));
+ }
+
public function testNonEnvelopeErrorBodyMapsToTypedException(): void
{
// The readiness probe answers 503 with {status, details}: no statusCode/message, and a
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 1ddbd7918..26e384dd0 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -75,11 +75,11 @@ A non-2xx response raises a typed `OpenWAApiError` subclass — `OpenWAAuthError
timeout raises `OpenWATimeoutError`. 503 is transient, but a catalog 503 can persist because
WhatsApp may never answer that query, so bound any retry. A 429 from the global rate limiter
lifts when its window expires (seconds for the per-second tier, up to an hour for the hourly
-tier by default); its delay is only in the `Retry-After` response header, which the error does
-not carry. A 429 whose body has `code: "SEND_PACING_LIMITED"` is not transient: do not retry it
-before the body's `retryAfterSeconds`, which can be hours. In a routed deployment only 503
-proves the request was never carried out: a forward that fails after the request reached the
-owner node answers 502 or 504.
+tier by default), and `.retry_after_seconds` carries its `Retry-After` header. A 429 whose
+`.code` is `"SEND_PACING_LIMITED"` is not transient: do not retry it before
+`.retry_after_seconds`, which then comes from the body and can be hours. Every API error also
+exposes the response `.headers`. In a routed deployment only 503 proves the request was never
+carried out: a forward that fails after the request reached the owner node answers 502 or 504.
```python
from openwa import OpenWANotFoundError
diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.py
index 8a2dffb85..2bf91346e 100644
--- a/sdk/python/openwa/_http.py
+++ b/sdk/python/openwa/_http.py
@@ -138,5 +138,5 @@ class HttpExecutor:
# rather than a success. Matches the JS transport's `!res.ok`.
if res.status_code >= 300:
context = f"{method} {path}"
- raise OpenWAApiError.from_response(res.status_code, res.text, context)
+ raise OpenWAApiError.from_response(res.status_code, res.text, context, headers=res.headers)
return res
diff --git a/sdk/python/openwa/errors.py b/sdk/python/openwa/errors.py
index 33c901bb6..e273d02f8 100644
--- a/sdk/python/openwa/errors.py
+++ b/sdk/python/openwa/errors.py
@@ -10,7 +10,10 @@ This module maps that to a typed, ergonomic error tree so callers can
from __future__ import annotations
-from typing import Any
+import math
+from datetime import datetime, timezone
+from email.utils import parsedate_to_datetime
+from typing import Any, Mapping
class OpenWAError(Exception):
@@ -24,16 +27,36 @@ class OpenWAApiError(OpenWAError):
status: HTTP status code.
body: Parsed JSON body if available, otherwise the raw text.
error_kind: Value of the ``error`` field in the NestJS envelope.
+ code: The body's machine-readable ``code`` (e.g. ``SEND_PACING_LIMITED``), if any.
+ retry_after_seconds: Seconds to wait before retrying: the body's ``retryAfterSeconds``
+ when present, else the ``Retry-After`` header (seconds or an HTTP date), else None.
+ headers: The response headers, when the error came from a response.
"""
- def __init__(self, message: str, status: int, body: Any = None, error_kind: str | None = None) -> None:
+ def __init__(
+ self,
+ message: str,
+ status: int,
+ body: Any = None,
+ error_kind: str | None = None,
+ *,
+ headers: Mapping[str, str] | None = None,
+ ) -> None:
super().__init__(message)
self.status = status
self.body = body
self.error_kind = error_kind
+ self.headers = headers
+ fields = body if isinstance(body, dict) else {}
+ code = fields.get("code")
+ self.code: str | None = code if isinstance(code, str) else None
+ header = next((v for k, v in (headers or {}).items() if k.lower() == "retry-after"), None)
+ self.retry_after_seconds = _retry_after_seconds(fields.get("retryAfterSeconds"), header)
@classmethod
- def from_response(cls, status_code: int, text: str, context: str) -> "OpenWAApiError":
+ def from_response(
+ cls, status_code: int, text: str, context: str, *, headers: Mapping[str, str] | None = None
+ ) -> "OpenWAApiError":
import json
body: Any = None
@@ -51,7 +74,7 @@ class OpenWAApiError(OpenWAError):
else:
message_text = str(raw_message)
message = f"OpenWA API {status_code} — {context}: {message_text}"
- return classify(status_code, message, body, envelope.get("error") if envelope else None)
+ return classify(status_code, message, body, envelope.get("error") if envelope else None, headers=headers)
class OpenWAAuthError(OpenWAApiError):
@@ -74,10 +97,10 @@ class OpenWARateLimitError(OpenWAApiError):
"""429 Too Many Requests.
The global rate limiter's 429 lifts when its window expires (seconds for the
- per-second tier, up to an hour for the hourly tier by default); its delay is
- only in the Retry-After response header, which this error does not carry. A
- 429 whose body has code "SEND_PACING_LIMITED" is not transient: do not retry
- it before the body's retryAfterSeconds, which can be hours.
+ per-second tier, up to an hour for the hourly tier by default), and
+ ``retry_after_seconds`` carries its Retry-After header. A 429 with code
+ "SEND_PACING_LIMITED" is not transient: do not retry it before
+ ``retry_after_seconds``, which then comes from the body and can be hours.
"""
@@ -107,7 +130,9 @@ class OpenWATimeoutError(OpenWAError):
self.timeout = timeout
-def classify(status: int, message: str, body: Any, error_kind: str | None) -> OpenWAApiError:
+def classify(
+ status: int, message: str, body: Any, error_kind: str | None, *, headers: Mapping[str, str] | None = None
+) -> OpenWAApiError:
"""Pick the most specific :class:`OpenWAApiError` subclass for a status."""
cls = {
401: OpenWAAuthError,
@@ -118,4 +143,26 @@ def classify(status: int, message: str, body: Any, error_kind: str | None) -> Op
501: OpenWANotImplementedError,
503: OpenWAServiceUnavailableError,
}.get(status, OpenWAApiError)
- return cls(message, status, body, error_kind)
+ return cls(message, status, body, error_kind, headers=headers)
+
+
+def _retry_after_seconds(from_body: Any, header: str | None) -> int | None:
+ """The body's ``retryAfterSeconds`` wins: send pacing puts its wait (possibly hours) only there,
+ and a header added by a proxy must not shorten it. Otherwise read ``Retry-After`` as seconds or
+ an HTTP date, clamped at 0."""
+ if isinstance(from_body, (int, float)) and not isinstance(from_body, bool) and 0 <= from_body < math.inf:
+ return math.ceil(from_body)
+ value = (header or "").strip()
+ if not value:
+ return None
+ if value.isascii() and value.isdigit():
+ return int(value)
+ try:
+ at = parsedate_to_datetime(value)
+ except (TypeError, ValueError, OverflowError):
+ return None
+ if at is None:
+ return None
+ if at.tzinfo is None:
+ at = at.replace(tzinfo=timezone.utc)
+ return max(0, math.ceil((at - datetime.now(timezone.utc)).total_seconds()))
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index dfb011aba..5839a1fc1 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -2,6 +2,9 @@
from __future__ import annotations
+import json
+import time
+
import httpx
import pytest
@@ -161,6 +164,50 @@ class TestClientCore:
with pytest.raises(OpenWANotFoundError):
make_client(backend).sessions.get("missing")
+ def test_error_exposes_code_retry_after_and_headers(self):
+ from email.utils import formatdate
+
+ from openwa.errors import OpenWARateLimitError
+
+ def fail(status: int, body: object = None, headers: dict[str, str] | None = None, text: str = "") -> OpenWAApiError:
+ content = json.dumps(body).encode() if body is not None else text.encode()
+ transport = httpx.MockTransport(lambda _: httpx.Response(status, content=content, headers=headers))
+ client = OpenWAClient(base_url="https://x", api_key="k", transport=transport)
+ with pytest.raises(OpenWAApiError) as caught:
+ client.sessions.list()
+ return caught.value
+
+ throttled = fail(429, {"statusCode": 429, "message": "ThrottlerException: Too Many Requests"}, {"Retry-After": "7"})
+ assert isinstance(throttled, OpenWARateLimitError)
+ assert throttled.retry_after_seconds == 7
+ assert throttled.code is None
+ assert throttled.headers is not None and throttled.headers["retry-after"] == "7"
+
+ # Send pacing puts its wait in the body; a header must not shorten it.
+ pacing = {
+ "statusCode": 429,
+ "error": "Too Many Requests",
+ "message": "Daily send cap reached",
+ "code": "SEND_PACING_LIMITED",
+ "retryAfterSeconds": 34521,
+ }
+ for headers in (None, {"Retry-After": "1"}):
+ err = fail(429, pacing, headers)
+ assert err.code == "SEND_PACING_LIMITED"
+ assert err.retry_after_seconds == 34521
+
+ dated = fail(503, headers={"Retry-After": formatdate(time.time() + 2, usegmt=True)})
+ assert dated.retry_after_seconds is not None and 0 <= dated.retry_after_seconds <= 3
+ assert fail(503, headers={"Retry-After": "soon"}).retry_after_seconds is None
+ # An out-of-range date overflows inside the stdlib parser; it is still just unparseable.
+ for huge in ("Mon, 01 Jan 99999999999999999999 00:00:00 GMT", "Fri, 1 Jan 2100 00:00:00 +99999999999999999999"):
+ assert fail(503, headers={"Retry-After": huge}).retry_after_seconds is None
+
+ logout = fail(502, {"statusCode": 502, "message": "x", "code": "SESSION_LOGOUT_INCOMPLETE"})
+ assert logout.code == "SESSION_LOGOUT_INCOMPLETE"
+ plain = fail(500, text="oops")
+ assert plain.code is None and plain.retry_after_seconds is None
+
def test_maps_503_to_service_unavailable(self):
# The gateway answers 503 when the engine never confirmed an operation: a transport failure,
# which is worth retrying, as a 429 is. It used to fall through to the base class while the
diff --git a/src/common/docs-sdk-rate-limit.spec.ts b/src/common/docs-sdk-rate-limit.spec.ts
new file mode 100644
index 000000000..7785862dc
--- /dev/null
+++ b/src/common/docs-sdk-rate-limit.spec.ts
@@ -0,0 +1,18 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+/**
+ * The global rate limiter has an hourly tier (`RATE_LIMIT_LONG_TTL`, one hour by default), so its
+ * 429 can last up to an hour. Every SDK README states that; one that promises the 429 clears
+ * within seconds sends its readers into a retry loop against an hour-long window.
+ */
+describe('SDK READMEs: global rate limiter 429 duration', () => {
+ const repoRoot = join(__dirname, '..', '..');
+ const readmes = ['javascript', 'python', 'php', 'go', 'java'].map(sdk => `sdk/${sdk}/README.md`);
+
+ it.each(readmes)('%s names the hourly tier and no seconds-only promise', path => {
+ const text = readFileSync(join(repoRoot, path), 'utf8').replace(/\s+/g, ' ');
+ expect(text).toContain('up to an hour for the hourly tier by default');
+ expect(text).not.toMatch(/clears within seconds/);
+ });
+});