docsResourcesError Codes

Error Codes Reference

Complete reference of all error codes returned by the Lorn AI API.


HTTP Status Codes

CodeNameDescription
200OKRequest succeeded
201CreatedResource created successfully
400Bad RequestInvalid request parameters
401UnauthorizedInvalid or missing API key
403ForbiddenAPI key lacks required permissions
404Not FoundResource does not exist
405Method Not AllowedInvalid operation for current state
409ConflictIdempotency key conflict
422Unprocessable EntityValid syntax but semantic errors
429Too Many RequestsRate limit exceeded
500Internal Server ErrorUnexpected server error
502Bad GatewayUpstream service error
503Service UnavailableService temporarily unavailable

Error Response Format

Standard Error

{
  "detail": "Error message describing what went wrong"
}

Structured Error

{
  "error": {
    "type": "invalid_request",
    "code": "missing_required_field",
    "message": "The 'items' field is required",
    "param": "items"
  }
}

Checkout Error with Messages

{
  "checkout_session": {
    "id": "cs_demo_abc123",
    "status": "not_ready_for_payment",
    "messages": [
      {
        "type": "error",
        "code": "out_of_stock",
        "path": "$.line_items[0]",
        "content_type": "plain",
        "content": "This item is no longer available."
      }
    ]
  }
}

Error Types

invalid_request

Client sent an invalid request.

CodeDescriptionSolution
missing_required_fieldRequired field not providedAdd the missing field
invalid_formatField has wrong formatCheck field format requirements
invalid_valueField value is invalidUse valid value
request_not_idempotentSame idempotency key, different paramsUse new idempotency key

authentication_error

Authentication failed.

CodeDescriptionSolution
invalid_api_keyAPI key is invalidCheck API key is correct
expired_api_keyAPI key has expiredRequest new API key
missing_api_keyNo API key providedAdd X-ACP-API-Key header

authorization_error

Authorization failed.

CodeDescriptionSolution
insufficient_permissionsKey lacks required permissionsRequest elevated permissions
resource_not_accessibleCannot access this resourceCheck resource ownership

not_found

Resource not found.

CodeDescriptionSolution
product_not_foundProduct ID doesn’t existVerify product ID
session_not_foundCheckout session doesn’t existCreate new session
variant_not_foundVariant SKU doesn’t existVerify variant SKU

rate_limit_exceeded

Too many requests.

CodeDescriptionSolution
rate_limit_exceededExceeded request rate limitWait and retry

processing_error

Server-side processing error.

CodeDescriptionSolution
internal_errorUnexpected server errorRetry request
database_errorDatabase operation failedRetry request

service_unavailable

Service temporarily unavailable.

CodeDescriptionSolution
backend_not_configuredBackend services not set upContact support
maintenanceService under maintenanceWait and retry

Checkout-Specific Errors

Product Errors

CodePathDescription
out_of_stock$.line_items[n]Product is out of stock
insufficient_inventory$.line_items[n]Not enough stock for quantity
product_unavailable$.line_items[n]Product no longer available
invalid_variant$.line_items[n]Variant doesn’t exist

Address Errors

CodePathDescription
invalid_address$.shipping_addressAddress validation failed
unsupported_region$.shipping_addressCannot ship to this region
missing_address$.shipping_addressShipping address required

Payment Errors

CodePathDescription
payment_declined$.payment_methodPayment was declined
invalid_payment_method$.payment_methodPayment method invalid
requires_3ds$.payment_method3D Secure required

State Errors

CodeDescription
session_completedCannot modify completed session
session_canceledCannot modify canceled session
cannot_cancelSession cannot be canceled

Handling Errors by Language

Python

import requests
 
try:
    response = requests.get(f"{BASE_URL}/acp/products/invalid_id", headers=HEADERS)
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    status = e.response.status_code
    body = e.response.json()
    
    if status == 400:
        print(f"Bad request: {body.get('detail')}")
    elif status == 401:
        print("Invalid API key")
    elif status == 404:
        print("Resource not found")
    elif status == 429:
        retry_after = e.response.headers.get('Retry-After', 60)
        print(f"Rate limited. Retry after {retry_after}s")
    elif status >= 500:
        print("Server error. Please retry.")
    else:
        print(f"Error {status}: {body}")

TypeScript

try {
  const response = await fetch(`${BASE_URL}/acp/products/invalid_id`, {
    headers: { "X-ACP-API-Key": API_KEY }
  });
  
  if (!response.ok) {
    const body = await response.json();
    
    switch (response.status) {
      case 400:
        console.error(`Bad request: ${body.detail}`);
        break;
      case 401:
        console.error("Invalid API key");
        break;
      case 404:
        console.error("Resource not found");
        break;
      case 429:
        const retryAfter = response.headers.get("Retry-After") || "60";
        console.error(`Rate limited. Retry after ${retryAfter}s`);
        break;
      default:
        console.error(`Error ${response.status}: ${JSON.stringify(body)}`);
    }
  }
} catch (error) {
  console.error("Network error:", error);
}

Java

try {
    String result = client.getProduct("invalid_id");
} catch (RuntimeException e) {
    String message = e.getMessage();
    
    if (message.contains("400")) {
        System.err.println("Bad request");
    } else if (message.contains("401")) {
        System.err.println("Invalid API key");
    } else if (message.contains("404")) {
        System.err.println("Resource not found");
    } else if (message.contains("429")) {
        System.err.println("Rate limited");
    } else if (message.contains("500") || message.contains("503")) {
        System.err.println("Server error - retry later");
    }
}

Go

_, err := client.GetProduct("invalid_id")
if err != nil {
    errStr := err.Error()
    
    switch {
    case strings.Contains(errStr, "400"):
        log.Println("Bad request")
    case strings.Contains(errStr, "401"):
        log.Println("Invalid API key")
    case strings.Contains(errStr, "404"):
        log.Println("Resource not found")
    case strings.Contains(errStr, "429"):
        log.Println("Rate limited")
    case strings.Contains(errStr, "500"), strings.Contains(errStr, "503"):
        log.Println("Server error - retry later")
    default:
        log.Printf("Error: %s\n", errStr)
    }
}

Retry Strategy

Retryable Errors

StatusRetryableStrategy
408YesImmediate retry
429YesWait for Retry-After header
500YesExponential backoff
502YesExponential backoff
503YesWait for Retry-After or exponential backoff
504YesExponential backoff

Non-Retryable Errors

StatusRetryableAction
400NoFix request
401NoFix authentication
403NoCheck permissions
404NoResource doesn’t exist
405NoInvalid operation
409NoHandle conflict
422NoFix request data

Exponential Backoff

import time
import random
 
def retry_with_backoff(func, max_retries=3, base_delay=1):
    for attempt in range(max_retries):
        try:
            return func()
        except RetryableError as e:
            if attempt == max_retries - 1:
                raise
            
            delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
            time.sleep(delay)

Common Issues

”Supabase not configured”

{
  "detail": "Supabase not configured. Set SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, and OPENAI_API_KEY."
}

Cause: Backend environment variables not set.

Solution: Contact support to verify backend configuration.

”Unknown product_id”

{
  "detail": "Unknown product_id prod_xyz"
}

Cause: Product ID doesn’t exist in catalog.

Solution:

  1. Verify the product ID from search results
  2. Ensure the product is still available
  3. Check for typos in product ID

”Checkout session not found”

{
  "detail": "Checkout session not found"
}

Cause: Session ID is invalid or expired.

Solution:

  1. Verify the session ID
  2. Create a new checkout session
  3. Sessions may expire after inactivity

”Cannot cancel session with status ‘completed’”

{
  "detail": "Cannot cancel session with status 'completed'"
}

Cause: Trying to cancel an already completed order.

Solution: Completed orders cannot be canceled via API. Use refund process instead.


Getting Help

If you encounter errors not covered here:

  1. Check the error message — Often contains specific guidance
  2. Review request format — Ensure JSON is valid and fields match spec
  3. Verify API version — Some errors may be version-specific
  4. Contact support — Include request ID and timestamp

Support email: mayank@lornai.com.com