Error Codes Reference

Last Updated: 2026-02-16


This document provides a complete reference of all error codes, HTTP status codes, and error responses returned by the cloak.business API.


Table of Contents#

  1. Error Response Format
  2. HTTP Status Codes
  3. Error Codes by Category
  4. Handling Errors
  5. Troubleshooting Guide

Error Response Format#

All API errors return a consistent JSON structure:

{
  "error": "Error type (short)",
  "message": "Human-readable description",
  "code": "MACHINE_READABLE_CODE",
  "details": {
    "field": "Additional context"
  }
}
FieldTypeDescription
errorstringShort error type identifier
messagestringHuman-readable explanation
codestringMachine-readable error code (optional)
detailsobjectAdditional context (optional)

HTTP Status Codes#

Success Codes#

CodeNameDescription
200OKRequest succeeded
201CreatedResource created successfully
204No ContentRequest succeeded, no response body

Client Error Codes#

CodeNameDescription
400Bad RequestInvalid request parameters
401UnauthorizedInvalid or missing authentication
402Payment RequiredInsufficient tokens
403ForbiddenFeature not available on plan
404Not FoundResource does not exist
409ConflictResource conflict (duplicate)
413Payload Too LargeRequest body exceeds limits
422Unprocessable EntityValidation failed
429Too Many RequestsRate limit exceeded

Server Error Codes#

CodeNameDescription
500Internal Server ErrorUnexpected server error
502Bad GatewayBackend service unavailable
503Service UnavailableService temporarily unavailable
504Gateway TimeoutBackend request timed out

Error Codes by Category#

Authentication Errors (401)#

CodeMessageCauseSolution
AUTH_MISSINGAuthorization header missingNo Authorization headerAdd Authorization: Bearer YOUR_KEY
AUTH_INVALIDInvalid API keyAPI key is malformed or revokedCheck key format, regenerate if needed
AUTH_EXPIREDToken expiredSession or API token expiredRe-authenticate or refresh token
AUTH_SCHEMEInvalid authorization schemeNot using Bearer schemeUse Bearer prefix

Example:

{
  "error": "Unauthorized",
  "message": "Invalid API key",
  "code": "AUTH_INVALID"
}

Fix:

# Verify your API key format
curl -H "Authorization: Bearer cb_your_key_here" ...

Token/Billing Errors (402)#

CodeMessageCauseSolution
INSUFFICIENT_TOKENSInsufficient tokensNot enough tokens for operationPurchase more tokens
TOKENS_EXHAUSTEDMonthly allocation exhaustedMonthly limit reachedWait for reset or upgrade
PAYMENT_REQUIREDPayment requiredAccount has unpaid balanceUpdate payment method

Example:

{
  "error": "Insufficient tokens",
  "message": "Operation requires 50 tokens, you have 23",
  "code": "INSUFFICIENT_TOKENS",
  "details": {
    "required": 50,
    "available": 23
  }
}

Fix:

Check your balance and purchase tokens if needed:

curl https://cloak.business/api/user/tokens \
  -H "Authorization: Bearer YOUR_KEY"

Plan/Feature Errors (403)#

CodeMessageCauseSolution
FEATURE_NOT_AVAILABLEFeature not availableFeature requires higher planUpgrade your plan
PLAN_LIMIT_EXCEEDEDPlan limit exceededExceeded plan-specific limitUpgrade or wait for reset
IMAGE_NOT_AVAILABLEImage redaction not availableImage features require Basic+Upgrade to Basic plan
BATCH_NOT_AVAILABLEBatch processing not availableBatch requires Basic+Upgrade to Basic plan

Example:

{
  "error": "Feature not available",
  "message": "Image redaction is not available on the Free plan. Please upgrade.",
  "code": "FEATURE_NOT_AVAILABLE",
  "details": {
    "feature": "image_redaction",
    "required_plan": "basic",
    "current_plan": "free"
  }
}

Validation Errors (400)#

CodeMessageCauseSolution
INVALID_REQUESTInvalid requestMalformed JSON or missing fieldsCheck request body
INVALID_LANGUAGEInvalid languageLanguage code not supportedUse ISO 639-1 code
INVALID_ENTITIESInvalid entitiesUnknown entity typeCheck entity names
INVALID_OPERATORInvalid operatorUnknown operator typeUse valid operator
INVALID_HASH_TYPEInvalid hash typeHash type not supportedUse sha256 or sha512
MISSING_FIELDRequired field missingRequired parameter not providedInclude required field

Example:

{
  "error": "Invalid request",
  "message": "Language must be a valid 2-letter ISO 639-1 code",
  "code": "INVALID_LANGUAGE",
  "details": {
    "provided": "english",
    "expected": "2-letter code (e.g., 'en', 'de')"
  }
}

Fix:

{
  "text": "Hello world",
  "language": "en"
}

Size Limit Errors (413)#

CodeMessageCauseSolution
TEXT_TOO_LONGText size limit exceededText exceeds plan limitSplit into smaller chunks
FILE_TOO_LARGEFile too largeFile exceeds 10 MB limitReduce file size
TOO_MANY_ENTITIESToo many entities>50 entities in requestReduce entity list
TOO_MANY_RECOGNIZERSToo many ad-hoc recognizers>50 recognizersReduce recognizer count
TOO_MANY_PATTERNSToo many patterns>200 total patternsReduce pattern count

Example:

{
  "error": "Text size limit exceeded",
  "message": "Text length 600000 exceeds plan limit of 500000 characters",
  "code": "TEXT_TOO_LONG",
  "details": {
    "provided": 600000,
    "limit": 500000,
    "plan": "basic"
  }
}

Plan Limits:

PlanMax Text LengthMax File Size
Free100,000 charsN/A
Basic500,000 chars10 MB
Professional1,000,000 chars10 MB
EnterpriseUnlimited50 MB

Rate Limit Errors (429)#

CodeMessageCauseSolution
RATE_LIMITEDRate limit exceededToo many requestsWait and retry
DAILY_LIMIT_EXCEEDEDDaily upload limit reachedDaily file limit hitWait until tomorrow
MONTHLY_LIMIT_EXCEEDEDMonthly upload limit reachedMonthly limit hitUpgrade or wait

Example:

{
  "error": "Rate limit exceeded",
  "message": "Too many requests. Please wait before retrying.",
  "code": "RATE_LIMITED",
  "retryAfter": 60
}

Response Headers:

Retry-After: 60
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1708099200

Fix:

Implement exponential backoff:

import time

def call_api_with_retry(func, max_retries=3):
    for attempt in range(max_retries):
        response = func()
        if response.status_code == 429:
            retry_after = int(response.headers.get("Retry-After", 60))
            time.sleep(retry_after)
            continue
        return response
    raise Exception("Max retries exceeded")

Service Errors (5xx)#

CodeMessageCauseSolution
MODEL_LOADINGLanguage model loadingModel being loadedRetry after delay
SERVICE_UNAVAILABLEService unavailableBackend downRetry later
INTERNAL_ERRORInternal server errorUnexpected errorContact support
TIMEOUTRequest timeoutProcessing took too longReduce input size

Example - Model Loading:

{
  "error": "MODEL_LOADING",
  "message": "Language model for 'ja' is being loaded. Please retry.",
  "retry_after": 30,
  "language": "ja"
}

Fix:

Large language models (Japanese, Chinese, Korean) may take 30-90 seconds to load on first use. Retry after the suggested delay:

import time

response = analyze(text, language="ja")
if response.status_code == 503 and response.json().get("error") == "MODEL_LOADING":
    retry_after = response.json().get("retry_after", 30)
    time.sleep(retry_after)
    response = analyze(text, language="ja")

Handling Errors#

Python Example#

import requests
from typing import Optional

class CloakAPIError(Exception):
    def __init__(self, status_code: int, error: str, message: str, code: Optional[str] = None):
        self.status_code = status_code
        self.error = error
        self.message = message
        self.code = code
        super().__init__(f"{status_code} {error}: {message}")

def call_api(endpoint: str, payload: dict) -> dict:
    response = requests.post(
        f"https://cloak.business/api{endpoint}",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=payload
    )

    if response.status_code >= 400:
        data = response.json()
        raise CloakAPIError(
            status_code=response.status_code,
            error=data.get("error", "Unknown"),
            message=data.get("message", "Unknown error"),
            code=data.get("code")
        )

    return response.json()

# Usage
try:
    result = call_api("/presidio/analyze", {"text": "Hello"})
except CloakAPIError as e:
    if e.code == "INSUFFICIENT_TOKENS":
        print("Need to purchase more tokens")
    elif e.code == "RATE_LIMITED":
        print("Rate limited, will retry")
    else:
        print(f"API error: {e}")

JavaScript Example#

class CloakAPIError extends Error {
  constructor(statusCode, error, message, code) {
    super(`${statusCode} ${error}: ${message}`);
    this.statusCode = statusCode;
    this.error = error;
    this.code = code;
  }
}

async function callAPI(endpoint, payload) {
  const response = await fetch(`https://cloak.business/api${endpoint}`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(payload)
  });

  const data = await response.json();

  if (!response.ok) {
    throw new CloakAPIError(
      response.status,
      data.error || "Unknown",
      data.message || "Unknown error",
      data.code
    );
  }

  return data;
}

// Usage
try {
  const result = await callAPI("/presidio/analyze", { text: "Hello" });
} catch (e) {
  if (e instanceof CloakAPIError) {
    switch (e.code) {
      case "INSUFFICIENT_TOKENS":
        console.log("Need more tokens");
        break;
      case "RATE_LIMITED":
        console.log("Will retry later");
        break;
      default:
        console.error(`API error: ${e.message}`);
    }
  }
}

Troubleshooting Guide#

"Unauthorized" (401)#

  1. Check API key format: Must start with cb_
  2. Check header: Must be Authorization: Bearer YOUR_KEY
  3. Verify key is active: Check Dashboard > API Keys
  4. Regenerate if needed: Create a new key

"Insufficient tokens" (402)#

  1. Check balance: GET /api/user/tokens
  2. Estimate cost: Analyze ~1 token/1000 chars + entities
  3. Purchase tokens: Dashboard > Billing > Buy Tokens

"Rate limit exceeded" (429)#

  1. Wait: Check Retry-After header
  2. Reduce frequency: Add delays between requests
  3. Batch requests: Use /batch for multiple texts
  4. Upgrade: Higher plans have higher limits

"Text too long" (413)#

  1. Check limit: See plan limits above
  2. Split text: Process in chunks
  3. Upgrade: Higher plans have higher limits

"Model loading" (503)#

  1. Wait: Models load on first use
  2. Retry: After retry_after seconds
  3. Pre-warm: Send a test request at startup

"Invalid language" (400)#

  1. Use ISO 639-1: 2-letter codes only
  2. Supported: en, de, fr, es, it, pt, nl, pl, ru, ja, zh, ko, etc.
  3. Check spelling: "en" not "english"

Support#

If you encounter an error not listed here or need assistance:

Include the following in support requests:

  • Error response (full JSON)
  • Request endpoint and parameters (without sensitive data)
  • Timestamp of the error
  • Your plan type

Document maintained by cloak.business