---
title: "Standard Error Codes & Matrix"
description: "Comprehensive reference matrix of standard machine error codes, HTTP status codes, and deterministic resolution actions."
---

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

# Standard Error Codes & Matrix

# Standard Error Codes & Matrix

Shaf REST API responses use standard HTTP status codes combined with machine-readable application error codes and deterministic mitigation paths.

---

## Error Response Format

All error responses return a standardized JSON error envelope:

```json
{
  "code": 40001,
  "message": "The destination URL is malformed or missing a valid protocol (http:// or https://).",
  "data": null,
  "requestId": "req_8f12a9c4e0b3"
}
```

Include the `requestId` when reporting unresolvable anomalies to Shaf technical support.

---

## 4xx Client Error Matrix

| HTTP Status | Code | Constant | Meaning | Deterministic Resolution Action |
| :--- | :---: | :--- | :--- | :--- |
| `400 Bad Request` | `40001` | `INVALID_URL` | Destination URL is malformed or lacks HTTP/HTTPS protocol. | Ensure URL begins with `http://` or `https://` and is under 2,048 characters. |
| `400 Bad Request` | `40002` | `INVALID_SLUG` | Slug contains illegal characters or exceeds 2,048 characters. | Restrict slugs to `[a-zA-Z0-9_-]` characters. |
| `400 Bad Request` | `40003` | `RESERVED_SLUG` | Slug collides with protected marketing or internal routing paths. | Choose an alternative slug that is not a reserved system path (`/api`, `/dashboard`, `/docs`). |
| `400 Bad Request` | `40004` | `INVALID_EXPIRY` | Expiration timestamp is in the past or non-numeric. | Provide a Unix timestamp in seconds strictly greater than `Date.now() / 1000`. |
| `400 Bad Request` | `40005` | `INVALID_PAYLOAD` | Request body JSON failed schema validation. | Inspect specific parameter errors returned in the error message string. |
| `400 Bad Request` | `40006` | `INVALID_SUBPATH_PREFIX` | Subpath reverse proxy prefix is missing leading slash or uses reserved tokens. | Ensure path prefix begins with `/` (e.g. `/go` or `/links`) and does not conflict with system paths. |
| `400 Bad Request` | `40007` | `INVALID_GEO_CONFIG` | Geotargeting country code is invalid. | Use uppercase two-letter ISO 3166-1 alpha-2 country codes (e.g. `US`, `GB`, `DE`). |
| `401 Unauthorized` | `40101` | `UNAUTHORIZED` | Missing or invalid `Authorization: Bearer <token>` header. | Verify the API key in [Settings > API Keys](https://shaf.app/docs/docs/how-to/integrations-and-developer/api-keys). |
| `401 Unauthorized` | `40102` | `TOKEN_EXPIRED` | API key or session token has exceeded its configured expiration date. | Generate a replacement token in the dashboard and rotate integration secrets. |
| `401 Unauthorized` | `40103` | `INVALID_TOKEN` | Bearer token signature is corrupt or unrecognized. | Ensure the full key string is provided without extra whitespace or truncation. |
| `403 Forbidden` | `40301` | `FORBIDDEN` | Token lacks necessary permission scope (e.g. read-only token attempting write). | Reissue the API key with `links:write` or `org:admin` scopes. |
| `403 Forbidden` | `40302` | `QUOTA_EXCEEDED` | Active link, domain, or seat limits have been reached for this workspace. | Upgrade your subscription plan or archive obsolete resources. |
| `403 Forbidden` | `40303` | `MALICIOUS_URL` | Target destination is flagged as phishing or malware by Google Safe Browsing. | Review destination URL security reputation. Shaf will not route to compromised endpoints. |
| `403 Forbidden` | `40304` | `SSO_ENFORCED` | Direct password/token authentication is disabled because SAML SSO is enforced. | Authenticate through your corporate identity provider (IdP). |
| `404 Not Found` | `40401` | `LINK_NOT_FOUND` | No active link matches the requested slug and domain combination. | Check spelling of slug and custom domain hostname. |
| `404 Not Found` | `40402` | `DOMAIN_NOT_FOUND` | Requested custom domain is not registered to the authenticated workspace. | Verify domain registration status via `GET /api/v1/domains`. |
| `404 Not Found` | `40403` | `MEMBER_NOT_FOUND` | User ID is not found in the organization member roster. | Check member ID formatting (`usr_...`). |
| `409 Conflict` | `40901` | `SLUG_EXISTS` | Slug is already allocated on the designated domain. | Use a different slug or dispatch `PATCH /api/v1/links/:slug` to update destination. |
| `409 Conflict` | `40902` | `DOMAIN_EXISTS` | Custom domain is already registered to another workspace. | Verify domain ownership via DNS TXT record or contact support for transfer. |
| `429 Too Many Requests`| `42901` | `RATE_LIMITED` | Sustained request rate exceeds plan threshold (e.g. 120 or 600 req/min). | Check `Retry-After` header and execute exponential backoff. |
| `429 Too Many Requests`| `42902` | `BURST_EXCEEDED` | High-frequency burst requests exceeded short-interval buffer (e.g. 30 req/5s). | Throttle client concurrency and serialize write pipelines. |

---

## 5xx Server Error Matrix

| HTTP Status | Code | Constant | Meaning | Deterministic Resolution Action |
| :--- | :---: | :--- | :--- | :--- |
| `500 Internal Error` | `50001` | `INTERNAL_ERROR` | Unexpected unhandled exception in edge runtime. | Retry with exponential backoff. If persistent, check [status.shaf.app](https://status.shaf.app). |
| `502 Bad Gateway` | `50201` | `UPSTREAM_UNAVAILABLE` | External dependency (Workers AI or Google Safe Browsing API) failed to respond. | Request can be safely retried immediately or with 1s backoff. |
| `503 Service Unavailable` | `50301` | `EDGE_UNAVAILABLE` | Cloudflare edge node undergoing maintenance or transient storage lock. | Retry request after backoff delay. |
| `504 Gateway Timeout` | `50401` | `D1_TIMEOUT` | Authoritative SQLite D1 query exceeded execution timeout. | Reduce batch operation size or add pagination limits. |

---

## Handling Rate Limits with Jittered Backoff

When receiving `HTTP 429 Too Many Requests`, use exponential backoff with full jitter to avoid synchronization storms across worker instances:

### TypeScript

```typescript
async function fetchWithRetry<T>(
  url: string,
  options: RequestInit,
  maxRetries = 4,
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.status !== 429) {
      if (!response.ok) {
        const err = await response.json();
        throw new Error(`API Error [${err.code}]: ${err.message}`);
      }
      return response.json();
    }

    const retryAfterHeader = response.headers.get("Retry-After");
    const baseDelayMs = retryAfterHeader
      ? parseInt(retryAfterHeader, 10) * 1000
      : Math.min(1000 * 2 ** attempt, 16000);

    // Add full jitter: random value between 0 and baseDelayMs
    const delay = Math.random() * baseDelayMs;
    await new Promise((resolve) => setTimeout(resolve, delay));
  }

  throw new Error("Max retries exceeded due to rate limiting.");
}
```

### Python

```python
import random
import time
import requests

def request_with_retry(method: str, url: str, **kwargs):
    max_retries = 4
    for attempt in range(max_retries + 1):
        response = requests.request(method, url, **kwargs)
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()

        retry_after = response.headers.get("Retry-After")
        if retry_after:
            base_delay = float(retry_after)
        else:
            base_delay = min(1.0 * (2 ** attempt), 16.0)

        delay = random.uniform(0, base_delay)
        time.sleep(delay)

    raise RuntimeError("Max retries exceeded due to rate limiting.")
```

Source: https://shaf.app/docs/reference/error-codes/index.mdx
