> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Handling

> Every error code the PromptGuard API returns, and how to handle each one

> [!NOTE]
>
> Branch on `error.code`. It is the machine-readable identifier and it is stable;
> `message` is for humans and can change. Every code on this page is checked
> against the codes the API actually emits, so a code you find here is one you
> can receive.

## The error envelope

Every error is a JSON object with a single `error` key:

```json theme={"system"}
{
  "error": {
    "message": "PromptGuard API key required. Please provide via X-API-Key header.",
    "type": "authentication_error",
    "code": "missing_api_key",
    "doc_url": "https://docs.promptguard.co/production/error-handling#missing_api_key"
  }
}
```

| Field | Always present | Meaning |
| - | - | - |
| `message` | Yes | Human-readable, safe to log and show a developer |
| `code` | Yes | What to branch on |
| `type` | Almost always | A broad category. The generic `HTTP_ERROR` and `INTERNAL_SERVER_ERROR` envelopes omit it |
| `doc_url` | On every code in the [reference below](#error-code-reference) | This page's entry for the code, for example `https://docs.promptguard.co/production/error-handling#missing_api_key`. Absent on a code the reference does not list, so do not depend on it |

Some codes add fields of their own, **at the top level of `error`**.
`retry_after`, for example, is `error.retry_after`. The fields each code adds
are shown in its section below. The one list-valued field is
[`invalid_request`](#invalid-request-422)'s `error.details`, one entry per
field that failed validation.

To correlate a failure with our logs, quote the `X-Request-ID` response header.
Security decisions also carry `X-PromptGuard-Event-ID`.

## Error code reference

| Code | Status | Retry? | Meaning |
| - | - | - | - |
| `missing_api_key` | 401 | No | No PromptGuard API key was sent, or, on the proxy (including `GET /api/v1/models`), no provider key was sent in `Authorization` and none is stored for the project or account; `message` then names the provider |
| `invalid_api_key` | 401 | No | The key is malformed or unknown, or, on the proxy, the upstream provider rejected *your provider key* |
| `disabled_api_key` | 401 | No | The key exists but has been disabled |
| `expired_api_key` | 401 | No | The key has passed its expiry (set at creation, or the grace window of a rotation) |
| `user_not_found` | 401 | No | The key is valid but the account it belongs to no longer exists (`/api/v1/api-keys` only). Create a new key from a current account |
| `user_disabled` | 403 | No | The account the key belongs to has been disabled (`/api/v1/api-keys` only). Contact support |
| `scope_denied` | 403 | No | The key's scopes do not permit this endpoint; `message` names the scope it needs |
| `read_only_key` | 403 | No | A [SIEM export key](https://docs.promptguard.co/integrations/siem-export.md#pull-with-an-export-key) can only read `/api/v1/alerts`, `/api/v1/interactions` and its stream |
| `invalid_cursor` | 400 | No | The `cursor` (or `Last-Event-ID`) passed to a [SIEM export](https://docs.promptguard.co/integrations/siem-export.md#pull-with-an-export-key) read was not one we issued; start again from `since` |
| `ip_not_allowed` | 403 | No | The caller's IP is not on the organization's IP allowlist |
| `ip_allowlist_error` | 403 | Yes, with backoff | The IP allowlist could not be checked, so the request was refused |
| `ip_reputation_blocked` | 403 | No | The caller's IP is on a network threat list (self-hosted deployments that enable it) |
| `access_list_block` | 403 | No | An access-list rule on the project refused the caller |
| `request_blocked` | 403 | No | The input scan blocked the request |
| `response_blocked` | 200 | No | The output scan blocked the completion (see [Blocked responses](#blocked-responses)) |
| `content_blocked` | SSE event | No | The output scan blocked a streamed completion |
| `missing_header` | 400 | No | A header the request needs was not sent; `message` and `param` name it. Today that is `X-Azure-Resource` on an [`azure/` model](https://docs.promptguard.co/integrations/providers/azure-openai) |
| `invalid_header` | 400 | No | A header is malformed: it contains non-ASCII characters (usually a pasted API key with a look-alike letter), an [`X-PromptGuard-Cache`](https://docs.promptguard.co/gateway/caching) value is not one we offer, or a [request tag](https://docs.promptguard.co/gateway/request-tags.md) breaks a limit. `param` names the header |
| `unknown_pii_type` | 400 | No | `POST /api/v1/security/redact`, was sent a `pii_types` entry it does not know; `message` lists the supported names. The hosted MCP server's `promptguard_redact` refuses the same way, as a tool error carrying this `code` |
| `invalid_preset` | 400 | No | A [red-team run](https://docs.promptguard.co/api-reference/security-endpoints.md#security-testing-red-team-endpoints) named a `target_preset` that does not exist; `valid_presets` lists the ones that do |
| `invalid_fallback_models` | 400 | No | The request's [fallback models](https://docs.promptguard.co/gateway/fallback-models.md) are not a list of 1 to 3 model names |
| `fallback_model_not_allowed` | 400 | No | A [fallback model](https://docs.promptguard.co/gateway/fallback-models.md) the request named is on a vendor with no provider key stored for the project or your account, or is on another vendor on an endpoint other than `/api/v1/chat/completions`. `message` names the model, the vendor and which of the two it was. A routing rule's fallback model is skipped instead, never refused |
| `overlay_pattern_can_stall` | 400 | No | A policy overlay adds a regular expression that takes too long to run; `message` names the part responsible. Rewrite the pattern; acknowledging a loosening does not override this |
| `overlay_weakens_protection` | 409 | No | Dashboard API: restoring a policy overlay version would weaken protection: it loosens or disables a detector below the project's preset, or blocks less than an overlay in force (the restored version's own scope's, or the one the project's devices run). `warnings` names each change; restore again with `acknowledge_loosening` to put it in force anyway. The API's own apply answers the same case with `overlay_loosens_core_detectors` |
| `overlay_candidate_already_running` | 409 | No | Dashboard API: the project already runs a Candidate overlay, and runs one at a time. Stop it first |
| `overlay_candidate_unavailable_on_hybrid` | 409 | No | Dashboard API: the project's Organization has a Hybrid data plane, which scans with its own engine and would never evaluate a Candidate overlay made here |
| `overlay_bands_invalid` | 400 | No | A policy overlay (applied, restored or run as a Candidate) would leave warn and block thresholds that cannot be honoured: a `warn_threshold` above the `block_threshold` it lands on, or bands on a guardrail that does not decide by them (only `prompt_injection` and `toxicity` do). `message` says which. Acknowledging a loosening does not override this |
| `overlay_candidate_start_limit_reached` | 409 | No | Dashboard API: the project has started the most Candidate overlays it may in the last 30 days (10). Run the one you have for longer, or restore a version directly |
| `overlay_loosens_core_detectors` | 409 | No | `POST /api/v1/overlays/apply`: the overlay weakens protection, by loosening or disabling a detector below the project's preset or by blocking less than an overlay in force (its scope's own, or the one the project's devices run). `warnings` names each change; re-submit with `acknowledge_loosening: true` to apply anyway. This response carries the code as both `code` and `error` |
| `overlay_corpus_unavailable` | 400 | No | `POST /api/v1/overlays/preview`: the request asked for the built-in sample corpus (`sample.kind` `corpus`, the default), which is not included in the hosted API or in self-hosted images. Send `sample.kind: "inline"` with your own prompts in `sample.texts` |
| `prompt_too_large` | 413 | No | The prompt exceeds the maximum size. On the [Guard API](https://docs.promptguard.co/api-reference/guard.md#long-conversations), only when the newest message does not fit on its own: older messages are left out and listed in `unscanned` instead |
| `token_limit_exceeded` | 413 | No | The prompt exceeds the project's per-request token limit |
| `request_body_too_large` | 413 | No | The Guard API request body exceeds the size limit |
| `api_key_rate_limit_admin_only` | 403 | No | Dashboard API: only an admin of a team organization can set or remove an API key's [own rate limit](https://docs.promptguard.co/production/rate-limits.md#per-key-limits) |
| `device_credential_rate_limit` | 409 | No | Dashboard API: the key is an enrolled device's credential, which is never rate limited, so it cannot take a limit of its own |
| `api_key_request_cap_admin_only` | 403 | No | Dashboard API: only an admin of a team organization can set or remove an API key's [monthly request cap](https://docs.promptguard.co/api-reference/api-keys.md#monthly-request-cap) |
| `device_credential_request_cap` | 409 | No | Dashboard API: the key is an enrolled device's credential, which is never held to a monthly request cap, so it cannot take one |
| `rule_not_suppressible` | 400 | No | Dashboard API: the [Suppression](https://docs.promptguard.co/api-reference/guard.md#suppressions) names a detector or rule that does not exist, or one that can never be suppressed (the ML injection classifier and every model or LLM judge of injection, the secret detectors, canary tokens, and your project's own rules). A finding's `rule.suppressible` says which can be. `message` says which case it was |
| `suppression_expiry_out_of_range` | 400 | No | Dashboard API: a Suppression's `expires_at` is not in the future, or is further away than the most a Suppression may last; `message` gives the limit |
| `suppression_limit_reached` | 409 | No | Dashboard API: the project already holds the most unexpired Suppressions it may (the listing's `limit`). Delete one, or let one expire |
| `finding_not_on_event` | 400 | No | Dashboard API: a Suppression filed with a false-positive report names a rule, or a matched text, other than the finding that decided the reported event. Name the event's own finding, from its `findings` |
| `suppression_unavailable_on_hybrid` | 409 | No | Dashboard API: the project's Organization has a Hybrid data plane, which scans with its own engine and never receives a Suppression, so one made here would not apply. See [Self-hosted vs Cloud](https://docs.promptguard.co/production/self-host-vs-cloud.md) |
| `upstream_spend_cap_unavailable_on_hybrid` | 409 | No | Dashboard API: the project's Organization has a Hybrid data plane, which sends requests to your provider itself, so a [spend cap](https://docs.promptguard.co/gateway/spend-caps.md) set here would never see that spend. See [Self-hosted vs Cloud](https://docs.promptguard.co/production/self-host-vs-cloud.md) |
| `upstream_spend_cap_reached` | 402 | Not until the month ends or the cap is raised | The project's monthly [spend cap](https://docs.promptguard.co/gateway/spend-caps.md) would be crossed by this request. `message` names the cap, the month's spend, what requests in flight hold, and what this request could cost. A lower `max_tokens` reserves less |
| `upstream_spend_cap_unpriced_model` | 400 | No | The project has a [spend cap](https://docs.promptguard.co/gateway/spend-caps.md) and the model, on the provider serving it, has no price PromptGuard can count, so it would spend uncounted. Use a priced model or remove the cap |
| `upstream_spend_cap_unavailable` | 503 | Yes, with backoff | The project has a [spend cap](https://docs.promptguard.co/gateway/spend-caps.md) and it could not be checked, so the request was not sent |
| `rate_limit_exceeded` | 429 | Yes, after `retry_after` | A per-minute request limit was hit (PromptGuard's own, or the provider's on the proxy) |
| `bot_detected` | 429 | Not automatically | The traffic pattern was classified as automated abuse; `retry_after` is included |
| `monthly_quota_exceeded` | 429 | Not in a loop | The plan's monthly request quota is spent |
| `api_key_request_cap_exceeded` | 429 | Not in a loop | This key's own [monthly request cap](https://docs.promptguard.co/api-reference/api-keys.md#monthly-request-cap) is reached; `resets_at` says when it resets. Your other keys are still served |
| `spending_limit_exceeded` | 429 | Not in a loop | The account's monthly spending cap is reached |
| `subscription_inactive` | 429 | **Never** | The subscription is cancelled, past due, unpaid or paused, or no plan covers the key's organization |
| `detection_unavailable` | 503 | Yes, with backoff | The project fails closed and the security scan could not run |
| `engine_unavailable` | 503 | Yes, with backoff | The security engine for a red-team run could not be started, so no run was performed and no block rate is reported; `detail` says why |
| `model_not_found` | 404 | No | The upstream provider does not know the model, or no provider serves a [fallback model](https://docs.promptguard.co/gateway/fallback-models.md) you named |
| `provider_error` | Provider's status | 5xx only | The upstream provider returned an error |
| `upstream_interrupted` | 502 | Yes | The provider's connection dropped partway through its answer, and every provider and [fallback model](https://docs.promptguard.co/gateway/fallback-models.md#streamed-requests) the request had was tried. Nothing was sent to you |
| `upstream_invalid_response` | 502 | Yes | The provider answered with a success status, but its body was not a completion: not JSON, or JSON that is not an object. Nothing was sent to you. `X-PromptGuard-Model-Used` names the model |
| `upstream_timeout` | 504 | Yes, with backoff | No provider answered within the time limit a proxied request's upstream attempts share, provider failover, a routing rule's `failover_provider` and [fallback models](https://docs.promptguard.co/gateway/fallback-models.md#one-time-limit-for-the-whole-request) included |
| `invalid_request` | 422 | No | The request body failed validation: a required field is missing, a field has the wrong type or length, or the body is not valid JSON. `error.details` lists each field (see [Invalid request](#invalid-request-422)) |
| `not_found` | 404 | No | No endpoint matches the method and path. Check the path against the [API reference](https://docs.promptguard.co/api-reference/introduction.md) |
| `HTTP_ERROR` | 4xx | No | A generic request error, such as a method an endpoint does not accept (405) or a resource a route could not find |
| `INTERNAL_SERVER_ERROR` | 500 | Yes, with backoff | An unexpected failure on our side; quote `error_id` to support |

> [!WARNING]
>
> Every `429` code shares one status. A client that retries every 429 will
> retry `subscription_inactive` forever, and will hammer a spent quota until the
> next billing month. Branch on `code` before you back off.

## Invalid request (422)

A body that does not match the endpoint's schema (here `POST /api/v1/guard`
sent `message` instead of `messages`) is refused before anything is scanned or
counted:

```json theme={"system"}
{
  "error": {
    "message": "The request is invalid: body.messages: Field required",
    "type": "invalid_request_error",
    "code": "invalid_request",
    "details": [
      {
        "type": "missing",
        "loc": ["body", "messages"],
        "msg": "Field required",
        "input": {"message": "hi"}
      }
    ],
    "error_id": "3f0b8c1e-6a0e-4d52-9a57-0c2a9a7f5b11",
    "doc_url": "https://docs.promptguard.co/production/error-handling#invalid_request"
  }
}
```

Each entry in `details` names the field by its path in `loc`, what is wrong
with it in `type` and `msg`, and the value it was sent in `input`, left out
when that value is longer than about 1 KB. Fix the
request; retrying it unchanged fails the same way.

> [!WARNING]
>
> Until 2027-02-11 a 422, and a 404 for a path no endpoint serves, also carry
> the framework's old top-level `detail` (the same list, or `"Not Found"`) beside
> `error`, and say so in their `Deprecation` and `Sunset` headers. Read
> `error.details` and `error.code` instead; `detail` is removed on that date
> ([Deprecations](https://docs.promptguard.co/versioning-and-support.md#deprecations-and-removals)).

## Authentication and authorization

### Missing or invalid key (401)

```json theme={"system"}
{
  "error": {
    "message": "Invalid API key",
    "type": "authentication_error",
    "code": "invalid_api_key"
  }
}
```

`missing_api_key`, `disabled_api_key` and `expired_api_key` have the same shape.
None is fixed by retrying: check that `PROMPTGUARD_API_KEY` is set, that the key
starts with `pg_live_`, and that it is still enabled and unexpired in the
dashboard. After a key rotation, `expired_api_key` means the old key's grace
window has closed.

On the proxy, an `invalid_api_key` whose message names a provider (for example
"Incorrect Anthropic API key provided") means the **provider** rejected the
provider key configured on your project, not your PromptGuard key.

### Scope denied (403)

A key created with restricted scopes, or a scan-only device credential, is
refused on endpoints outside those scopes:

```json theme={"system"}
{
  "error": {
    "message": "This endpoint needs the `usage:read` scope, which this API key does not hold. Create a key that includes it, or use an unrestricted key.",
    "type": "insufficient_scope",
    "code": "scope_denied"
  }
}
```

The message names the scope the endpoint needs, as `<group>:<level>`. In the
dashboard, create a key with **Restrict key** and give it that group: for
`usage:read`, **Usage** at **Read**. A key made with the dashboard's defaults
holds `scan` and `proxy` only.

## Rate limits and quotas

### Rate limit exceeded (429)

```json theme={"system"}
{
  "error": {
    "message": "Rate limit exceeded. Please retry later.",
    "type": "rate_limit_exceeded",
    "code": "rate_limit_exceeded",
    "retry_after": 42
  }
}
```

`retry_after` is in seconds and matches the `Retry-After` header. When the
**provider** rate-limits a proxied request, the code is the same but `type` is
`rate_limit_error`, there is no `retry_after` in the body, and the provider's
own `Retry-After` header is passed through, so read the header first.

### Monthly quota exceeded (429)

```json theme={"system"}
{
  "error": {
    "message": "This month's $5.00 of usage credit is used ($5.00 at list prices). Upgrade to Developer for $20 of usage credit a month.",
    "type": "quota_exceeded",
    "code": "monthly_quota_exceeded",
    "current_plan": "free",
    "requests_used": 4210,
    "requests_limit": null,
    "credit_usd": 5.0,
    "credit_used_usd": 5.000412,
    "credit_remaining_usd": 0.0,
    "upgrade_url": "https://app.promptguard.co/dashboard/billing",
    "retry_after": 1209600
  }
}
```

Here `retry_after` is the number of seconds until the credit resets at the start
of the next month, often days. Surface `upgrade_url` or `on_demand_url` instead
of sleeping. `credit_usd`, `credit_used_usd` and `credit_remaining_usd` report the
month's usage credit, and `requests_limit` is `null`. `on_demand_url` is present
only on plans that sell overage; on Free it is absent and the message names only
the upgrade.

### Spending limit exceeded (429)

```json theme={"system"}
{
  "error": {
    "message": "Monthly spending limit of $100.00 exceeded. Current spending: $99.99. Please increase your spending limit or wait until next billing cycle.",
    "type": "spending_limit_exceeded",
    "code": "spending_limit_exceeded",
    "current_plan": "pro",
    "current_spending": 99.99,
    "spending_limit": 100.0,
    "settings_url": "https://app.promptguard.co/dashboard/spending",
    "retry_after": 1209600
  }
}
```

### Subscription inactive (429)

```json theme={"system"}
{
  "error": {
    "message": "Your pro subscription is not active (status: past_due). Update your payment method to settle the outstanding invoice.",
    "type": "subscription_inactive",
    "code": "subscription_inactive",
    "current_plan": "pro",
    "subscription_status": "past_due",
    "reactivate_url": "https://app.promptguard.co/dashboard/billing"
  }
}
```

There is deliberately no `retry_after`: waiting does not fix this. Nothing
changes until the subscription is reactivated at `reactivate_url`.

`subscription_status` is `none` when no plan covers the key's organization at
all: a provider answered for its bill and no longer does, and the organization
has no owner of its own. Nothing at `reactivate_url` changes that one. Contact
support.

### Retrying correctly

```javascript theme={"system"}
const RETRYABLE_CODES = new Set([
  'rate_limit_exceeded',
  'detection_unavailable',
  'INTERNAL_SERVER_ERROR',
]);

function retryDelayMs(response, body, attempt) {
  // Prefer the header: it is present on PromptGuard's own 429s and passed
  // through from the provider on proxied ones.
  const header = Number(response.headers.get('retry-after'));
  if (header > 0) return header * 1000;
  if (body.error.retry_after > 0) return body.error.retry_after * 1000;
  return Math.min(1000 * 2 ** attempt, 30000) + Math.random() * 1000;
}

async function callWithRetry(request, maxRetries = 3) {
  for (let attempt = 0; ; attempt++) {
    const response = await request();
    if (response.ok) return response;

    const body = await response.json();
    const code = body.error?.code;

    const retryable =
      RETRYABLE_CODES.has(code) ||
      (code === 'provider_error' && response.status >= 500);

    if (!retryable || attempt >= maxRetries) {
      throw Object.assign(new Error(body.error.message), {
        status: response.status,
        code,
        error: body.error,
      });
    }
    await new Promise((r) => setTimeout(r, retryDelayMs(response, body, attempt)));
  }
}
```

`monthly_quota_exceeded`, `api_key_request_cap_exceeded`, `spending_limit_exceeded`
and `subscription_inactive` are left out on purpose: each needs a person, not a
retry. So is `bot_detected`:
it carries `retry_after`, but an automatic retry loop is the behaviour that was
flagged, so surface it instead.

## Security blocks

### Request blocked (403)

When the input scan blocks a proxied request, PromptGuard returns **HTTP 403**:

```json theme={"system"}
{
  "error": {
    "message": "Request blocked by security policy.",
    "type": "policy_violation",
    "code": "request_blocked",
    "event_id": "ac0ed289-1921-4d56-880b-063585836aea",
    "dashboard_url": "https://app.promptguard.co/dashboard/projects/{project_id}/interactions/ac0ed289-1921-4d56-880b-063585836aea"
  }
}
```

`dashboard_url` is present when the dashboard URL is configured. The threat
category is not in the body; read the `X-PromptGuard-Threat-Type` and
`X-PromptGuard-Confidence` response headers, and open the event in the dashboard
under **Projects → Interactions** for the full audit record.

The Guard API (`POST /api/v1/guard`) does not use this envelope: a blocked
decision there is a normal `200` response with `decision: "block"`.

### Blocked responses

When the **output** scan blocks a non-streamed completion, the body carries
`code: "response_blocked"` with the same fields as `request_blocked`:

```json theme={"system"}
{
  "error": {
    "message": "Response blocked by security policy.",
    "type": "policy_violation",
    "code": "response_blocked",
    "event_id": "ac0ed289-1921-4d56-880b-063585836aea"
  }
}
```

> [!WARNING]
>
> This body is currently delivered with **HTTP 200**, not 403. A client that only
> inspects the status code will treat it as a completion with no `choices`. Check
> for `error` in every successful proxy body.

### Blocked streamed responses

With `"stream": true`, the output scan runs on the full accumulated body before
any byte is emitted. There is no status code left to change by then, so a block
is delivered as a terminating SSE error event, and it carries
`type: "content_filter"` with `code: "content_blocked"`:

```json theme={"system"}
{
  "error": {
    "message": "Response blocked by security policy.",
    "type": "content_filter",
    "code": "content_blocked",
    "event_id": "ac0ed289-1921-4d56-880b-063585836aea",
    "dashboard_url": "https://app.promptguard.co/dashboard/projects/{project_id}/interactions/ac0ed289-1921-4d56-880b-063585836aea"
  }
}
```

No part of the completion is written when this happens, so the event is the
whole response. Branch on all three block codes:

```javascript theme={"system"}
const BLOCK_CODES = new Set([
  'request_blocked',    // input scan, 403
  'response_blocked',   // output scan, non-streaming
  'content_blocked',    // output scan, streaming
]);

const isBlocked = (body) => BLOCK_CODES.has(body?.error?.code);
```

Show the end user a neutral message and log `event_id`. Do not try to "clean"
a blocked prompt with your own regexes and resend it: a rewrite that slips past
the scan is exactly the evasion the scan exists to catch.

### Detection unavailable (503)

A project configured to **fail closed** refuses to forward a request the scan
could not evaluate:

```json theme={"system"}
{
  "error": {
    "message": "Security evaluation failed and this project is configured to fail closed, so the request was not forwarded. Retry shortly.",
    "type": "detection_unavailable",
    "code": "detection_unavailable",
    "detail": "TimeoutError"
  }
}
```

This is our outage, not a verdict on your content. Retry with backoff.

## Provider errors

On the proxy, an error from the upstream provider is passed through **with the
provider's status code** and PromptGuard's envelope. That holds for a streamed
request too: when the provider refuses it, no stream begins, and you get the
error as JSON with the provider's status rather than a `200` event stream:

```json theme={"system"}
{
  "error": {
    "message": "anthropic API is currently experiencing issues. Please try again later.",
    "type": "server_error",
    "code": "provider_error",
    "param": null
  },
  "status": 503
}
```

| Provider status | `code` | `type` |
| - | - | - |
| 401 | `invalid_api_key` | `authentication_error` |
| 404 | `model_not_found` | `invalid_request_error` |
| 429 | `rate_limit_exceeded` | `rate_limit_error` |
| 5xx | `provider_error` | `server_error` |
| Other 4xx | `provider_error` | `invalid_request_error` |

Retry only the 5xx `provider_error`. The provider's request id and rate-limit
headers are passed through, so quote the provider's request id to their support.

## Unexpected errors (500)

```json theme={"system"}
{
  "error": {
    "code": "INTERNAL_SERVER_ERROR",
    "message": "An unexpected error occurred",
    "error_id": "3f0b8c1e-6a0e-4d52-9a57-0c2a9a7f5b11"
  }
}
```

`error_id` equals the `X-Request-ID` header. Quote it to
[support](mailto:support@promptguard.co).

## Network errors

Connection failures never reach PromptGuard, so they carry no envelope. With
`fetch` in Node.js the socket error is on `err.cause`:

```javascript theme={"system"}
const SOCKET_ERRORS = ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND'];

function isNetworkError(err) {
  return SOCKET_ERRORS.includes(err.cause?.code);
}
```

Retry these with exponential backoff, the same as a 5xx.

## Testing your error handling

Build fixtures from the real envelopes above rather than inventing codes, so a
test cannot pass against a code the API never sends:

```javascript theme={"system"}
function promptGuardError(status, error, headers = {}) {
  return new Response(JSON.stringify({ error }), {
    status,
    headers: { 'content-type': 'application/json', ...headers },
  });
}

test('retries a rate limit after Retry-After', async () => {
  const request = jest.fn()
    .mockResolvedValueOnce(promptGuardError(429, {
      message: 'Rate limit exceeded. Please retry later.',
      type: 'rate_limit_exceeded',
      code: 'rate_limit_exceeded',
      retry_after: 1,
    }, { 'retry-after': '1' }))
    .mockResolvedValueOnce(new Response('{}', { status: 200 }));

  await callWithRetry(request);
  expect(request).toHaveBeenCalledTimes(2);
});

test('does not retry an inactive subscription', async () => {
  const request = jest.fn().mockResolvedValue(promptGuardError(429, {
    message: 'Your pro subscription is not active (status: cancelled).',
    type: 'subscription_inactive',
    code: 'subscription_inactive',
  }));

  await expect(callWithRetry(request)).rejects.toMatchObject({ code: 'subscription_inactive' });
  expect(request).toHaveBeenCalledTimes(1);
});
```

## Next Steps

> [card] [Best Practices](https://docs.promptguard.co/production/best-practices.md)
>
> Production deployment and reliability best practices

> [card] [Rate Limits](https://docs.promptguard.co/production/rate-limits.md)
>
> Understanding and managing API rate limits

> [card] [Troubleshooting](https://docs.promptguard.co/production/troubleshooting.md)
>
> Common issues and debugging techniques

> [card] [Monitoring](https://docs.promptguard.co/platform/dashboard.md)
>
> Set up comprehensive monitoring and alerts


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.